The NSLayoutAnchor class is a factory class for creating NSLayoutConstraint objects using a fluent API. Use these constraints to programatically define your layout using Auto Layout.
Language
- Swift
- Objective-C
SDKs
- iOS 9.0+
- macOS 10.11+
- tvOS 9.0+
Overview
Instead of creating NSLayoutConstraint objects directly, start with a UIView, NSView, or UILayoutGuide object you wish to constrain, and select one of that object’s anchor properties. These properties correspond to the main NSLayoutAttribute values used in Auto Layout, and provide an appropriate NSLayoutAnchor subclass for creating constraints to that attribute. Use the anchor’s methods to construct your constraint.
Note
UIView does not provide anchor properties for the layout margin attributes. Instead, the layoutMarginsGuide property provides a UILayoutGuide object that represents these margins. Use the guide’s anchor properties to create your constraints.
// Creating constraints using NSLayoutConstraint
NSLayoutConstraint(item: subview,
attribute: .Leading,
relatedBy: .Equal,
toItem: view,
attribute: .LeadingMargin,
multiplier: 1.0,
constant: 0.0).active = true
NSLayoutConstraint(item: subview,
attribute: .Trailing,
relatedBy: .Equal,
toItem: view,
attribute: .TrailingMargin,
multiplier: 1.0,
constant: 0.0).active = true
// Creating the same constraints using Layout Anchors
let margins = view.layoutMarginsGuide
subview.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor).active = true
subview.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor).active = true
As you can see from these examples, the NSLayoutAnchor class provides several advantages over using the NSLayoutConstraint API directly.
The code is cleaner, more concise, and easier to read.
The
NSLayoutAttributesubclasses provide additional type checking, preventing you from creating invalid constraints.
Note
While the NSLayoutAnchor class provides additional type checking, it is still possible to create invalid constraints. For example, the compiler allows you to constrain one view’s leadingAnchor with another view’s leftAnchor, since they are both NSLayoutXAxisAnchor instances. However, Auto Layout does not allow constraints that mix leading and trailing attributes with left or right attributes. As a result, this constraint crashes at runtime.
For more information on the anchor properties, see bottomAnchor in the UIView, NSView, or UILayoutGuide.
Note
You never use the NSLayoutAnchor class directly. Instead, use one of its subclasses, based on the type of constraint you wish to create.
Use
NSLayoutXAxisAnchorto create horizontal constraints.Use
NSLayoutYAxisAnchorto create vertical constraints.Use
NSLayoutDimensionto create constraints that affect the view’s height or width.
However, since you access NSLayoutAnchor objects using the anchor properties of a UIView, NSView, or UILayoutGuide, a correct subclass is automatically provided.