I have the default NSWindow created in a new application which has a single NSView. I then create a new NSViewController which has it's own XIB and a view. In the app delegate I do the obvious
self.mainViewController = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
[self.window.contentView addSubview:self.mainViewController.view];
self.mainViewController.view.frame = ((NSView*)self.window.contentView).bounds;
OK, how do I set a constraint in the new way to have my subview keep its size identical to the Window, i.e. it's superview. It doesn't seem to work automatically. Autoresizessubviews is ON for both views.
Basically, you need to constrain four things:
If the visual constraint isn't working out for you, you can build these four constraints individually in code. Use the method +constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:
constant:
to specify exact relationships between different views' attributes. For example, constraint #1 above might be expressed by:
[NSLayoutConstraint constraintWithItem:mySubview
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:mySuperview
attribute:NSLayoutAttributeLeading
multiplier:1.0f
constant:0.0f]
and #3 might be:
[NSLayoutConstraint constraintWithItem:mySubview
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:mySuperview
attribute:NSLayoutAttributeWidth
multiplier:1.0f
constant:0.0f]
Once you've built up those four constraints, you can add them to your superview as needed.
Note that there are multiple ways to achieve the same effect as above:
You can also probably come up with the same constraints in a visual representation, as in Peter Hosey's answer. For example, an equal-width constraint might look like @"[mySubview(==mySuperview)]"
with the appropriate views dictionary.
Keep in mind that the Auto Layout Guide is a wealth of information about constraints, including how to debug them when things go wrong.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With