Apple's documentation on creating Auto Layout constraints between a view and one of the layout guides only shows an example using VFL.
Is there any way to create these constraints programmatically without VFL (using NSLayoutConstraint
's other API or similar)?
(Note: I'm specifically asking about doing this in code, not in Interface Builder. And I don't want the calculated length
of the guide set as a static constant on a constraint, I want a constraint where changes to the layout guide length would automatically cause the constrained view to adjust position.)
Auto Layout defines your user interface using a series of constraints. Constraints typically represent a relationship between two views. Auto Layout then calculates the size and location of each view based on these constraints. This produces layouts that dynamically respond to both internal and external changes.
There are three main options for setting up Auto Layout constraints in Interface Builder: You can control-drag between views, you can use the Pin and Align tools, and you can let Interface Builder set up the constraints for you and then edit or modify the results.
To create constraints select the button and click the Align icon in the auto layout menu. A popover menu will appear, check both “Horizontal in container” and “Vertically in container” options to center the button on the screen. Then click the “Add 2 Constraints” button. Run the application.
For a UIButton
that you want to place 20 points below the UIViewController.topLayoutGuide
you create the NSLayoutConstraint
like so:
[NSLayoutConstraint constraintWithItem:self.button attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.topLayoutGuide attribute:NSLayoutAttributeBottom multiplier:1.0 constant:20.0];
With iOS 9 you can also create the NSLayoutConstraint
this way:
[self.button.topAnchor constraintEqualToAnchor:self.topLayoutGuide.bottomAnchor constant:20.0];
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