Changes

Jump to: navigation, search

Implementing iOS 9 Auto Layout Constraints in Code

3 bytes added, 21:22, 15 December 2015
no edit summary
 
In addition to using Interface Builder, it is also possible to create Auto Layout constraints directly within the code of an application. These approaches, however, are not necessarily mutually exclusive. There are, for example, situations where a layout will be constructed using a combination of Interface Builder and manual coding. Furthermore, some types of constraint cannot yet be implemented in Interface Builder, constraints that cross view hierarchies being a prime example. Interface Builder is also of limited use when user interfaces are created dynamically at run time.
In order to create a constraint, an instance of the NSLayoutConstraint class must be created and initialized with the appropriate settings for the Auto Layout behavior it is to implement. This is achieved by calling the constraintWithItem method and passing through a set of arguments for the constraint.
When considering this syntax, it is helpful to recall the way in which constraints can be represented using linear equations (as outlined in [[An Introduction to Auto Layout in iOS 9]]) because the elements of the equation match the arguments used to create an NSLayoutConstraint instance.
Consider, for example, the following constraint expressed as an equation:

Navigation menu