In the post “iOS: Defining a fixed or constant width or height constraint programmatically” , we programmatically added constraints that will ensure a fixed with and height for a view. This time, we will programmatically add constraints that will fit a view to its superview. This is especially useful if we have a container view that must occupy up the whole screen.
I have a view (let’s call this containerView
) which is programmatically added as a subview of a UIViewController’s main view (this is self.view
when called within the UIViewController).
Since I can’t define the constraints in Storyboard, I need to create the Auto Layout constraints programmatically.
The following code is added to the implementation file of the UIViewController:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
- (void)updateViewConstraints { [super updateViewConstraints]; [self.view addConstraint:[NSLayoutConstraint constraintWithItem:containerView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]]; [self.view addConstraint:[NSLayoutConstraint constraintWithItem:containerView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0.0]]; [self.view addConstraint:[NSLayoutConstraint constraintWithItem:containerView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]]; [self.view addConstraint:[NSLayoutConstraint constraintWithItem:containerView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0.0]]; } |
We added the constraints in updateViewConstraints
as specified in https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/AdoptingaFull-ScreenLayout/AdoptingaFull-ScreenLayout.html
Is it thisContainerView or is it pageView?
Thank you for pointing that out. I have updated the references to pageView (now containerView).
good
Why did you prefer setting the margins to 0 instead of making height and width equal?
Hi @ctietze
If I am not mistaken, setting “height and width equal” alone is not sufficient. You will need to define X and Y-related constraints for your view (e.g. X = half of width of superview or center of superview).
Margins, in my opinion, are much easier to remember and understand.