Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Auto Layout constraints to topLayoutGuide and bottomLayoutGuide in code

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.)

like image 440
smileyborg Avatar asked Oct 04 '13 06:10

smileyborg


People also ask

What are auto layout constraints?

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.

How do I create a constraint in Autolayout?

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.

How do I add a layout constraint in Xcode?

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.


1 Answers

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]; 
like image 189
Jamie McDaniel Avatar answered Oct 21 '22 02:10

Jamie McDaniel