Reputation: 6933
I am trying to use auto layout with size classes. I have a basic page with UIImageView as background and UIButton (with image as background). There are total of 6 constraints: 0 space for top/right/bottom/left for UIImageView and X center align and 230 for top space on UIButton. Here is what the interface builder looks like:
Her is what the preview looks like:
However, this is what I get when I run application on simulator (or device):
I cannot figure out why the constraints are not being executed? I should mention that this behavior is experienced when I try to set up auto layout in the .xib file. If I try to do same thing in the project that has storyboard, everything seems to be in order for simulator and real device.
Upvotes: 1
Views: 652
Reputation: 1502
How are you loading the view from xib?
e.g. Assuming your view is in a file called View.xib, I can recreate your problem with
- (void)viewDidLoad {
[super viewDidLoad];
UIView *v = [[NSBundle mainBundle] loadNibNamed:@"View" owner:self options:nil][0];
[self.view addSubview:v];
}
The reason this doesn't work, is because there is nothing telling auto layout to position and size the view to fill the screen, so the view just fits to its contents - which will be the size of the background image (because you have the constraints pinning the image to its parent view).
To fix it, first ensure the view is using auto layout by setting translatesAutoresizingMaskIntoConstraints = NO
(it defaults to YES otherwise, when loading from XIB) and then pin the view to its parent:
- (void)viewDidLoad {
[super viewDidLoad];
UIView *v = [[NSBundle mainBundle] loadNibNamed:@"View"
owner:self
options:nil][0];
[self.view addSubview:v];
v.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view]|"
options:0
metrics:nil
views:@{@"view": v}]];
[self.view addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|"
options:0
metrics:nil
views:@{@"view": v}]];
}
Upvotes: 3