Auto Layout for UIScrollView w/ 2 Child Views - ios

I have a scroll view that's set up inside a storyboard with auto layout constraints so that it fills the entire view. The scroll view contains two views managed by UIViewControllers instantiated from nibs. The code to include these subviews:
- (void)viewDidLoad {
[super viewDidLoad];
ContentViewController *contentVC = [ContentViewController new];
[[NSBundle mainBundle] loadNibNamed:#"ContentView" owner:contentVC options:nil];
self.scrollView.delegate = self;
[self addChildViewController:contentVC];
[self.scrollView addSubview:contentVC.contentTC.view];
[contentVC didMoveToParentViewController:self];
[self addChildViewController:contentVC.contentTC];
self.view.layer.borderColor = [[UIColor blackColor] CGColor];
self.view.layer.borderWidth = 5.0;
self.scrollView.layer.borderColor = [[UIColor blueColor] CGColor];
self.scrollView.layer.borderWidth = 5.0;
CGRect adminFrame = contentVC.view.frame;
adminFrame.origin.x = adminFrame.size.width;
ShareViewController *shareViewController = [[ShareViewController alloc] initWithNibName:#"ShareView" bundle:nil];
[self addChildViewController:shareViewController];
[self.scrollView addSubview:shareViewController.view];
shareViewController.view.frame = adminFrame;
CGRect shareFrame = shareViewController.view.frame;
shareFrame.origin.x = shareFrame.size.width;
[self.view addSubview:self.scrollView];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.scrollView
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeRight
multiplier:1.0
constant:0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.scrollView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:0]];
// 4) Finally set the size of the scroll view that contains the frames
CGFloat scrollWidth = 2 * self.view.frame.size.width;
CGFloat scrollHeight = self.view.frame.size.height;
self.scrollView.contentSize = CGSizeMake(scrollWidth, scrollHeight);
self.scrollView.pagingEnabled = YES;
self.scrollView.showsHorizontalScrollIndicator = NO;
self.scrollView.bounces = NO;
Don't have the ability to post an image, but here's a link to what it looks like:
dropbox.com/s/e84ya3ffrdzytac/Screenshot%202015-08-19%2011.52.15.png
In the iphone 6+ simulator, the scrollview is smaller in both width and height than the window, so there's white space on the right and bottom.
In the iPhone 4S simulator, the width is correct, but the subviews are longer than the window, which means that they'll scroll down. This only works in the iPhone 5, even though all of the views are inferred and not set up for 4-inch screens.
Apologies if this is a redundant question, but I've been searching through SO and banging my head against the wall for two days now, help would be appreciated.
** EDIT: UPDATED CODE AND BEHAVIOR: **
- (void)viewDidLoad {
[super viewDidLoad];
ContentViewController *contentVC = [ContentViewController new];
[[NSBundle mainBundle] loadNibNamed:#"ContentView" owner:contentVC options:nil];
self.scrollView.delegate = self;
self.scrollView.pagingEnabled = YES;
self.scrollView.showsHorizontalScrollIndicator = NO;
self.scrollView.bounces = NO;
self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:self.scrollView];
UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width * 2, self.view.frame.size.height)];
[self.scrollView addSubview:contentView];
[self addChildViewController:contentVC];
[contentView addSubview:contentVC.contentTC.view];
[contentVC didMoveToParentViewController:self];
[self addChildViewController:contentVC.contentTC];
CGRect adminFrame = contentVC.view.frame;
adminFrame.origin.x = adminFrame.size.width;
ShareViewController *shareViewController = [[ShareViewController alloc] initWithNibName:#"ShareView" bundle:nil];
[self addChildViewController:shareViewController];
[contentView addSubview:shareViewController.view];
shareViewController.view.frame = adminFrame;
self.view.layer.borderColor = [[UIColor blackColor] CGColor];
self.view.layer.borderWidth = 3;
self.scrollView.layer.borderColor = [[UIColor blueColor] CGColor];
self.scrollView.layer.borderWidth = 5;
contentView.layer.borderColor = [[UIColor greenColor] CGColor];
contentView.layer.borderWidth = 7;
CGRect shareFrame = shareViewController.view.frame;
shareFrame.origin.x = shareFrame.size.width;
[self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[v]|" options:0 metrics:nil views:#{#"v" : contentView}]];
[self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[v]|" options:0 metrics:nil views:#{#"v" : contentView}]];
Results: dropbox.com/s/29zwwn6inmdvz0e/Screenshot%202015-08-19%2014.27.47.png?dl=0 , dropbox.com/s/rqsdk9yubq84ph6/Screenshot%202015-08-19%2014.28.14.png?dl=0
Here's an image of the constraints from the storyboard: dropbox.com/s/8c5wkfw81sqd8ij/Screenshot%202015-08-19%2014.28.47.png?dl=0 (pinning edges to superview)

bound your scrollview from left,right,top and bottom then it look fine.
and it will look like..
here is code that i written with yours
(void)viewDidLoad
{
[super viewDidLoad];
UIViewController *contentVC = [[UIViewController alloc]init];
contentVC.view.backgroundColor = [UIColor greenColor];
self.scrollView.delegate = self;
[self addChildViewController:contentVC];
[self.scrollView addSubview:contentVC.view];
[contentVC didMoveToParentViewController:self];
[self addChildViewController:contentVC];
self.view.layer.borderColor = [[UIColor blackColor] CGColor];
self.view.layer.borderWidth = 5.0;
self.scrollView.layer.borderColor = [[UIColor blueColor] CGColor];
self.scrollView.layer.borderWidth = 5.0;
CGRect adminFrame = contentVC.view.frame;
adminFrame.origin.x = adminFrame.size.width;
UIViewController *shareViewController = [[UIViewController alloc] init];
shareViewController.view.backgroundColor = [UIColor grayColor];
[self addChildViewController:shareViewController];
[self.scrollView addSubview:shareViewController.view];
shareViewController.view.frame = adminFrame;
CGRect shareFrame = shareViewController.view.frame;
shareFrame.origin.x = shareFrame.size.width;
[self.view addSubview:self.scrollView];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.scrollView
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeRight
multiplier:1.0
constant:0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.scrollView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:0]];
// 4) Finally set the size of the scroll view that contains the frames
CGFloat scrollWidth = 2 * self.view.frame.size.width;
CGFloat scrollHeight = self.view.frame.size.height;
self.scrollView.contentSize = CGSizeMake(scrollWidth, scrollHeight);
self.scrollView.pagingEnabled = YES;
self.scrollView.showsHorizontalScrollIndicator = NO;
self.scrollView.bounces = NO;
}

Related

View not found in container hierarchy crash while adding View constraints programatically

Although the crash message is very clear but I have checked my code and everything seems to be looking fine. My only worry is because I am setting constraints on a view which is being set as accessory view for keyboard, could that be a reason why entire view hierarchy is not set properly.
Here is what I am doing:
Step 1: Create a custom accessory view (a number bar from 0 to 9) and put it on top of regular keyboard.
MyAccessoryView *anAccessoryView = [[MyAccessoryView alloc] initWithFrame:CGRectMake(0, 0, 320, 46.0f)];
anAccessoryView.delegate = self;
self.textField.inputAccessoryView = anAccessoryView;
Step 2: In custom accessory view (subview of UIView), add buttons and related handling. Add them to super view and then call a method after a delay of 1 second to add constraints.
- (id)initWithFrame:(CGRect)iFrame {
if (self = [super initWithFrame:iFrame]) {
[self refresh];
self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
}
[self setExclusiveTouch:YES];
return self;
}
- (void)refresh {
if (!self.layoutController) {
self.layoutController = [[MyAccessoryViewLayoutController alloc] init];
}
self.backgroundColor = [self.layoutController colorForNumericInputAccessory:self];
self.userInteractionEnabled = YES;
NSMutableArray *buttonsArray = [NSMutableArray arrayWithCapacity:10];
// Adding number keys to the accessory view and setting thier properties
for (NSInteger i = 1; i < 11; i++) {
MyAccessoryViewNumericButton *aKeyboardButton = [MyAccessoryViewNumericButton buttonWithType:UIButtonTypeCustom];
aKeyboardButton.tag = i;
aKeyboardButton.frame = CGRectMake(0, 0, 32.0, 44);
[aKeyboardButton setTitle: [NSString stringWithFormat:#"%ld", (long)i % 10] forState:UIControlStateNormal];
NSString *aButtonImageTitle = [self.layoutController buttonNormalStateImageNameForIndex:(i % 10) forNumericInputAccessory:self];
[aKeyboardButton setBackgroundImage:[UIImage imageNamed:aButtonImageTitle] forState:UIControlStateNormal];
aKeyboardButton.backgroundColor = [UIColor clearColor];
[aKeyboardButton setTitleColor:[UIColor blackColor] forState: UIControlStateNormal];
[aKeyboardButton setExclusiveTouch:YES];
aKeyboardButton.titleLabel.font = [self.layoutController fontForButtonTitlesForNumericInputAccessory:self];
if (self.layoutController.interfaceIdiom == UIUserInterfaceIdiomPhone) {
aKeyboardButton.titleLabel.textAlignment = NSTextAlignmentCenter;
} else {
NSString *aButtonHighlightedImageTitle = [self.layoutController buttonHighlightedStateImageNameForIndex:(i % 10) forNumericInputAccessory:self];
[aKeyboardButton setBackgroundImage:[UIImage imageNamed:aButtonHighlightedImageTitle] forState:UIControlStateHighlighted];
}
aKeyboardButton.hidden = NO;
aKeyboardButton.enabled = YES;
aKeyboardButton.tag = i;
[aKeyboardButton addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:aKeyboardButton];
[buttonsArray addObject:aKeyboardButton];
if (self.layoutController.interfaceIdiom == UIUserInterfaceIdiomPhone) {
UIImage *aPressedButtonImage = [UIImage imageNamed:[self.layoutController buttonHighlightedStateImageNameForIndex:(i % 10) forNumericInputAccessory:self]];
CGRect aPressedButtonViewFrame = [self.layoutController frameForPressedButtonViewWithIndex:(i % 10) forNumericInputAccessory:self];
UIView *aPressedButtonView = [[UIView alloc] initWithFrame:aPressedButtonViewFrame];
aPressedButtonView.backgroundColor = [UIColor clearColor];
aPressedButtonView.userInteractionEnabled = YES;
aPressedButtonView.hidden = YES;
UIImageView *aPressedButtonImageView = [[UIImageView alloc] initWithImage:aPressedButtonImage];
aPressedButtonImageView.frame = CGRectMake(0.0, 0.0, aPressedButtonViewFrame.size.width, aPressedButtonViewFrame.size.height);
aPressedButtonImageView.contentMode = UIViewContentModeBottom;
aPressedButtonImageView.backgroundColor = [UIColor clearColor];
CGRect aPressedButtonLabelFrame = [self.layoutController frameForPressedButtonLabelWithIndex:(i % 10) forNumericInputAccessory:self];
UILabel *aPressedButtonLabel = [[UILabel alloc] initWithFrame:aPressedButtonLabelFrame];
aPressedButtonLabel.backgroundColor = [UIColor clearColor];
aPressedButtonLabel.text = [NSString stringWithFormat: #"%ld", (long)i % 10];
aPressedButtonLabel.textAlignment = NSTextAlignmentCenter;
aPressedButtonView.tag = i + 100;
aPressedButtonLabel.font = [UIFont fontWithName: #"Helvetica-Bold" size: 44.0f];
aPressedButtonLabel.shadowColor = [UIColor colorWithRed: 0.95f green: 0.95f blue: 0.95f alpha: 1.0f];
aPressedButtonLabel.shadowOffset = CGSizeMake(0.0f, 0.75f);
if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication]statusBarOrientation])) {
aPressedButtonImageView.frame = CGRectMake(aPressedButtonImageView.frame.origin.x, aPressedButtonImageView.frame.origin.y - 2.0f, aPressedButtonImageView.frame.size.width, aPressedButtonImageView.frame.size.height);
}
[aPressedButtonView addSubview:aPressedButtonImageView];
[aPressedButtonView addSubview:aPressedButtonLabel];
[self addSubview:aPressedButtonView];
}
}
CALayer *aLightGreyBorder = [CALayer layer];
aLightGreyBorder.frame = CGRectMake(self.bounds.origin.x, self.bounds.origin.y + 1.0f, self.bounds.size.width, 1.0f);
UIColor *aColor = [UIColor colorWithRed:178.0f/255.0f green:184.0f/255.0f blue:191.0f/255.0f alpha:1.0f];
aLightGreyBorder.backgroundColor = [aColor CGColor];
[self.layer insertSublayer:aLightGreyBorder atIndex:0];
CALayer *aDarkGreyBorder = [CALayer layer];
aDarkGreyBorder.frame = CGRectMake(self.bounds.origin.x, self.bounds.origin.y, self.bounds.size.width, 1.0f);
UIColor *aSecondColor;
aSecondColor = [UIColor colorWithRed:100.0f/255.0f green:100.0f/255.0f blue:100.0f/255.0f alpha:1.0f];
aDarkGreyBorder.backgroundColor = [aSecondColor CGColor];
[self.layer insertSublayer:aDarkGreyBorder atIndex:0];
if (self.layoutController.interfaceIdiom == UIUserInterfaceIdiomPhone) {
for (UIView *aPressedButtonView in [self subviews]) {
if ([aPressedButtonView isMemberOfClass:[UIView class]]) {
[self bringSubviewToFront:aPressedButtonView];
}
}
}
// Now lets add constaints
[self performSelector:#selector(addConstraintsForButtons:) withObject:buttonsArray afterDelay:1.0];
}
Step 3: Add constraints to all buttons (0 to 9). Here, I am showing only first 2 buttons.
- (void)addConstraintsForButtons:(NSMutableArray *)iButtons {
// First Button
MyAccessoryViewNumericButton *firstButton = (MyAccessoryViewNumericButton *)iButtons[0];
// Left edge constraint for First button
NSLayoutConstraint *leading =[NSLayoutConstraint
constraintWithItem:firstButton
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeTrailing
multiplier:1.0f
constant:4.f];
[self addConstraint:leading];
// Middle in the super view
NSLayoutConstraint *vertical =[NSLayoutConstraint
constraintWithItem:firstButton
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterY
multiplier:1.0f
constant:0];
[self addConstraint:vertical];
// Width-Height Constraint for First button
[self addWHContraintForButton:firstButton];
// Second Button
MyAccessoryViewNumericButton *secondButton = (MyAccessoryViewNumericButton *)iButtons[1];
// Left edge constraint for First button
NSLayoutConstraint *secondLeading =[NSLayoutConstraint
constraintWithItem:secondButton
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:firstButton
attribute:NSLayoutAttributeTrailing
multiplier:1.0f
constant:4.f];
[secondButton addConstraint:secondLeading];
// Middle in the super view
NSLayoutConstraint *secondVertical =[NSLayoutConstraint
constraintWithItem:secondButton
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:firstButton
attribute:NSLayoutAttributeCenterY
multiplier:1.0f
constant:0];
[secondButton addConstraint:secondVertical];
// Width-Height Constraint for Second button
[self addWHContraintForButton:secondButton];
// Add constaints to rest of the buttons...
}
- (void)addWHContraintForButton:(MyAccessoryViewNumericButton *)iButton {
CGFloat buttonWidth = 32.0f;
CGFloat buttonHeight = 44.0f;
// Height Constraint
NSLayoutConstraint *height = [NSLayoutConstraint
constraintWithItem:iButton
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:0
multiplier:0
constant:buttonHeight];
// Width Constraint
NSLayoutConstraint *width = [NSLayoutConstraint
constraintWithItem:iButton
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:0
multiplier:0
constant:buttonWidth];
[iButton addConstraint:height];
[iButton addConstraint:width];
}
But when I run this code, it crashes with following message:
View not found in container hierarchy: <MyAccessoryViewNumericButton: 0x7fb506036f90; baseClass = UIButton; frame = (0 0; 32 44); opaque = NO; tag = 1; layer = <CALayer: 0x7fb506039c70>>
That view's superview: <MyAccessoryView: 0x7fb503ddfb50; frame = (0 0; 320 46); autoresize = W; layer = <CALayer: 0x7fb503dc1fe0>>
This is what I see when debug this (tried by setting constraints in keyboardDidShow: and didMoveToSuperview methods):
(lldb) po [secondButton superview]
<MyAccessoryView: 0x7fcd6d04f6c0; frame = (0 0; 320 46); autoresize = W; layer = <CALayer: 0x7fcd6adf5ed0>>
(lldb) po [[secondButton superview] superview]
<UIInputSetHostView: 0x7fcd6d0346c0; frame = (0 522; 320 262); layer = <CALayer: 0x7fcd6adef270>>
(lldb) po [[[secondButton superview] superview] superview]
<UIInputSetContainerView: 0x7fcd6d014000; frame = (0 0; 320 568); layer = <CALayer: 0x7fcd6add78d0>>
(lldb) po [[[[secondButton superview] superview] superview] superview]
<UITextEffectsWindow: 0x7fcd6d033c30; frame = (0 0; 320 568); opaque = NO; autoresize = W+H; layer = <UIWindowLayer: 0x7fcd6d034250>>
(lldb) po [[[[[secondButton superview] superview] superview] superview] superview]
0x0000000000000000
Although view has a parent. Can someone please advise here.

Objective-C add more UIButton horizontally

I am using a open source UIAlertView.View is
I want to add more button like horizontally, one in left side and another in right of BYE button, like this one
my using source-code are bellow
-(void)popUPView{
UIView* contentView = [[UIView alloc] init];
contentView.translatesAutoresizingMaskIntoConstraints = NO;
contentView.backgroundColor = [UIColor klcLightGreenColor];
contentView.layer.cornerRadius = 12.0;
UILabel* dismissLabel = [[UILabel alloc] init];
dismissLabel.translatesAutoresizingMaskIntoConstraints = NO;
dismissLabel.backgroundColor = [UIColor clearColor];
dismissLabel.textColor = [UIColor whiteColor];
dismissLabel.font = [UIFont boldSystemFontOfSize:32.0];
dismissLabel.text = #"Hi.";
UIButton* dismissButton = [UIButton buttonWithType:UIButtonTypeCustom];
dismissButton.translatesAutoresizingMaskIntoConstraints = NO;
dismissButton.contentEdgeInsets = UIEdgeInsetsMake(10, 20, 10, 20);
dismissButton.backgroundColor = [UIColor klcGreenColor];
[dismissButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[dismissButton setTitleColor:[[dismissButton titleColorForState:UIControlStateNormal] colorWithAlphaComponent:0.5] forState:UIControlStateHighlighted];
dismissButton.titleLabel.font = [UIFont boldSystemFontOfSize:16.0];
[dismissButton setTitle:#"Bye" forState:UIControlStateNormal];
dismissButton.layer.cornerRadius = 6.0;
[contentView addSubview:dismissLabel];
[contentView addSubview:dismissButton];
NSDictionary* views = NSDictionaryOfVariableBindings(contentView, dismissButton, dismissLabel);
[contentView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:#"V:|-(16)-[dismissLabel]-(10)-[dismissButton]-(24)-|"
options:NSLayoutFormatAlignAllCenterX
metrics:nil
views:views]];
[contentView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-(36)-[dismissLabel]-(36)-|"
options:0
metrics:nil
views:views]];
KLCPopup *popup = [KLCPopup popupWithContentView:contentView
showType:KLCPopupShowTypeShrinkIn
dismissType:KLCPopupDismissTypeShrinkOut
maskType:KLCPopupMaskTypeDimmed
dismissOnBackgroundTouch:TRUE
dismissOnContentTouch:FALSE];
[popup show];
}
would you kindly help me how to solve this problem . Thanks is advance
For this you must set proper leading/trailing values ,
leftView.trailing = rightView.leading
for example if you want to align a new view to the right , you would do something like this
UIView *viewToAllign = yourView;
UIView *view = [[UIView alloc] init];
imageViewOn.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:view];
NSLayoutConstraint *leading = [NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:viewToAllign
attribute:NSLayoutAttributeTrailing
multiplier:1
constant:SPACING_BETWEEN_VIEWS];
or if you want to align something on the left , just switch layout attributes
UIView *viewToAllign = yourView;
UIView *view = [[UIView alloc] init];
imageViewOn.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:view];
NSLayoutConstraint *leading = [NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:viewToAllign
attribute:NSLayoutAttributeLeading
multiplier:1
constant:SPACING_BETWEEN_VIEWS];
then you have to create other constraints ( height , width , top and bottom )
after this , you can add constraints to your container view

UILabel is not centered in my UIView

I'm adding a UILabel to a UIView on initialization and the label will not center itself. I've tried centering it is layoutSubviews and adding constraints programmatically with no luck. When it appears it is about 200 pixels to the left of the center. Here is my code. Thanks in advance.
- (instancetype)initWithTitle:(NSString *)title andBody:(NSString *)body Andwidth:(CGFloat)width {
self = [super initWithFrame:CGRectMake(0, 0, width, 60)];
if (self) {
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, 60)];
containerView.backgroundColor = [UIColor orangeColor];
[self addSubview:containerView];
self.winningLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0, 300, 40)];
self.winningLabel.textColor = [UIColor whiteColor];
self.winningLabel.font = [UIFont fontWithName:#"Avenir" size:30];
self.winningLabel.backgroundColor = [UIColor clearColor];
self.winningLabel.lineBreakMode = NSLineBreakByTruncatingTail;
self.winningLabel.numberOfLines = 2;
self.winningLabel.text = #"YOU WIN";
self.winningLabel.hidden = YES;
[containerView addSubview:self.winningLabel];
NSLayoutConstraint *xCenterConstraint = [NSLayoutConstraint constraintWithItem:self.winningLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
[self addConstraint:xCenterConstraint];
NSLayoutConstraint *yCenterConstraint = [NSLayoutConstraint constraintWithItem:self.winningLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
[self addConstraint:yCenterConstraint];
}
return self;
}
- (void)layoutSubviews {
[self.winningLabel setCenter:self.center];
}
I think you forget the text alignment. By default the text in a label is aligned to the left. If you want it to be in the center, you should specify it explicitly.
self.winningLabel.textAlignment = NSTextAlignmentCenter;

how to set subview of UIScrollView using autolayout

i am trying to implement Horizontal scrollview with ten views.
its working fine in portrait mode but i want same scenario in landscape too.
can anyone help me by which constraint i can achieve this?
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.title=#"Demo.....";
self.myScrollView.pagingEnabled = YES;
NSInteger numberOfViews = 10;
for (int i = 0; i < numberOfViews; i++) {
CGFloat myOrigin = i * self.view.frame.size.width;
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(myOrigin, 0, self.view.frame.size.width, self.view.frame.size.height)];
myView.backgroundColor = [UIColor purpleColor];
CGRect myFrame = CGRectMake(10.0f, 70.0f, 200.0f, 25.0f);
UILabel *myLabel = [[UILabel alloc] initWithFrame:myFrame];
myLabel.translatesAutoresizingMaskIntoConstraints = NO;
myLabel.text = [NSString stringWithFormat:#"This is page number %d", i];
myLabel.font = [UIFont boldSystemFontOfSize:16.0f];
myLabel.textAlignment = NSTextAlignmentLeft;
[myView addSubview:myLabel];
//set the scroll view delegate to self so that we can listen for changes
self.myScrollView.delegate = self;
//add the subview to the scroll view
[self.myScrollView addSubview:myView];
NSLayoutConstraint *constraintLeft = [NSLayoutConstraint constraintWithItem:myView
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.myScrollView
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:0.0];
// 0px to the right of the UIScrollView
NSLayoutConstraint *constraintRight = [NSLayoutConstraint constraintWithItem:myView
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:self.myScrollView
attribute:NSLayoutAttributeRight
multiplier:1.0
constant:0.0];
[self.myScrollView addConstraint:constraintLeft];
[self.myScrollView addConstraint:constraintRight];
}
//set the content size of the scroll view, we keep the height same so it will only
//scroll horizontally
self.myScrollView.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews,
self.view.frame.size.height);
//we set the origin to the 3rd page
CGPoint scrollPoint = CGPointMake(self.view.frame.size.width * 2, 0);
//change the scroll view offset the the 3rd page so it will start from there
[myScrollView setContentOffset:scrollPoint animated:YES];
[self.view addSubview:self.myScrollView];
}
in my above code,
ten view is completely added into scrollview and working fine in portrait mode but when i change the orientation to horizontal it will not resize and not scrolled.
You need to tie subviews width constraint equal to scrollView width
for (UIView *subView in subViews)
{
NSLayoutConstraint *constraintEqualWidth = [NSLayoutConstraint constraintWithItem:subView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self.myScrollView
attribute:NSLayoutAttributeWidth
multiplier:1.0
constant:0.0];
[subView addConstraint:constraintEqualWidth];
}

adding NSLayoutConstraint makes views disappear

I have a simple view (controller) with two subviews:
- (void)viewDidLoad {
[super viewDidLoad];
UIView *viewA = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
viewA.translatesAutoresizingMaskIntoConstraints = NO;
viewA.backgroundColor = [UIColor redColor];
[self.view addSubview:viewA];
UIView *viewB = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
viewB.translatesAutoresizingMaskIntoConstraints = NO;
viewB.backgroundColor = [UIColor grayColor];
[self.view addSubview:viewB];
}
Of course they are overlapping at this point (i can only see viewB). So I add a constraint to make viewB go below viewA, like this:
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:viewB
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:viewA
attribute:NSLayoutAttributeBottom
multiplier:1.f
constant:0]];
This makes both views disappear. What am I doing wrong?
Thanks!
When using constraints, you should do everything with constraints (no setting of frames), so adding one constraint isn't enough to define you positions and sizes. I'm not sure why adding the one constraint negated the sizes you set for the views, but it seems that it does. You should do something like this to fully describe the views,
- (void)viewDidLoad {
[super viewDidLoad];
UIView *viewA = [UIView new];
viewA.translatesAutoresizingMaskIntoConstraints = NO;
viewA.backgroundColor = [UIColor redColor];
[self.view addSubview:viewA];
UIView *viewB = [UIView new];
viewB.translatesAutoresizingMaskIntoConstraints = NO;
viewB.backgroundColor = [UIColor grayColor];
[self.view addSubview:viewB];
NSDictionary *dict = NSDictionaryOfVariableBindings(viewA,viewB);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"|[viewA(==50)]" options:0 metrics:nil views:dict]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"[viewB(==50)]" options:0 metrics:nil views:dict]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[viewA(==50)][viewB(==50)]" options:NSLayoutFormatAlignAllLeft metrics:nil views:dict]];
}

Resources