Creating Auto Layout constraints to topLayoutGuide and bottomLayoutGuide in code

smileyborg picture smileyborg · Oct 4, 2013 · Viewed 27.8k times · Source

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

Answer

Jamie McDaniel picture Jamie McDaniel · Nov 5, 2013

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];