Auto Layout programmatically with NSLayoutAnchor
May 22, 2016

Auto Layout programmatically can sometimes be pain in the ass, especially if you use vanilla
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
let margins = view.layoutMarginsGuide
subview.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor).active = true
subview.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor).active = true
NSLayoutAnchor FTW
Working with
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
There are more ways you could use them though I am leaving it to you to explore ;)