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


Solution 1:

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

Solution 2:

To supplement @JamieMcDaniel's answer, the Swift + iOS9 version would be:

self.button.topAnchor
    .constraintEqualToAnchor( self.topLayoutGuide.bottomAnchor ).active = true

Don't forget the .active = true part as otherwise the constraint doesn't kick in automatically.