I am programmatically building a view and using autolayout, no interface builder at all. In a custom ScrollView controller, I am adding a UILabel and a UIButton as subviews. I want to align the label to the left of the screen, and the button to the right of the screen. For some reason, my button only aligns to the left of my scrollview. I've pared down my code so that it's only these two labels and I can't understand why it won't align to the right.
HWScrollViewController.m (How I'm initializing the main scroll view)
- (void)loadView
{
self.scrollView = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.scrollView.delegate = self;
self.view = self.scrollView;
}
HWListingDetailViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *priceLabel = [[UILabel alloc] init];
UIButton *favouriteButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
[priceLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[favouriteButton setTranslatesAutoresizingMaskIntoConstraints:NO];
[priceLabel setText:@"$125.00"];
[favouriteButton setTitle:@"Add to Favourites" forState:UIControlStateNormal];
[self.view addSubview:priceLabel];
[self.view addSubview:favouriteButton];
[self.view addConstraints:@[
[NSLayoutConstraint constraintWithItem:priceLabel
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1
constant:0],
[NSLayoutConstraint constraintWithItem:priceLabel
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeft
multiplier:1
constant:5],
[NSLayoutConstraint constraintWithItem:favouriteButton
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1
constant:0],
[NSLayoutConstraint constraintWithItem:favouriteButton
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeRight
multiplier:1
constant:5],
}
As you can see, the green price label is aligned correctly, but the red button is way off of the lefthand side of the screen. (I gave it 5 pixels of offset to show where it was.) So, why is the right side of the scrollview actually the left side? How can I properly align to the right of the screen? Where did I go wrong? This is driving me crazy!
Thanks for any help!
Final layout images:
I'm hoping for the final layout to be something like this:
and I would expect it to look like this if rotated to landscape: