Auto Layout programmatically with NSLayoutAnchor

May 22, 2016

Auto Layout programmatically with NSLayoutAnchor

Auto Layout programmatically can sometimes be pain in the ass, especially if you use vanilla NSLayoutConstraint. The way you should use them is a daunting process of boilerplate code. This is the very reason why we have so many frameworks on GitHub to ease our lives doing iOS Auto Layout programmatically.

Lets have a look how it is being done 'old-style':

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

iOS 9 brought us may new features and one of them - new and easier way doing Auto Layout programmatically with NSLayoutAnchor. So here how the very same code above looks like with layout anchors:

let margins = view.layoutMarginsGuide
subview.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor).active = true
subview.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor).active = true

NSLayoutAnchor FTW

Working with NSLayoutAnchors is extremely easy. Suppose we want have a UILabel and we want to center it by Y and X axes right in the middle of the screen. All you have to do is this:

let margins = view.layoutMarginsGuide
myLabel.translatesAutoresizingMaskIntoConstraints = false
myLabel.centerXAnchor.constraintEqualToAnchor(margins.centerXAnchor).active = true
myLabel.centerYAnchor.constraintEqualToAnchor(margins.centerYAnchor).active = true

Now suppose you want to make this label's width being 50:

myLabel.widthAnchor.constraintEqualToConstant(50.0).active = true

Or you might want to now stick your label to the top of the view and its bottom with 50 points margin:

myLabel.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 50).active = true
myLabel.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor, constant: -50).active = true

And again - it just works. Much less code and much less to worry about. You might be wondering though what is LayoutMarginGuide? The thing is that you have to use them in case you want to stick your subviews to the UIView object, because only UIStackView has layoutAnchors so that you can attach subviews directly to the stackView, otheriwse - use layoutMarginsGuide.

There are more ways you could use them though I am leaving it to you to explore ;)

Comments

comments powered by Disqus