Adding constraints programmatically is a verbose endeavor.
Several libraries try to solve this by adding an additional layer between your code and Auto Layout. (PureLayout,Masonry, SnapKit, Lyt, Cartography, and others.)
While they make some things easier, they still require you to learn a new system with new quirks.
Instead, I use MiniLayout — one short file that simply takes the verbosity out of AutoLayout. It does this by using default values for most of NSLayoutConstraint’s parameters, and by compressing the cumbersome view.addConstraint( NSLayoutConstraint(...) )
into a single call.
Examples:
Put label
over textField
// using MiniLayout:
view.constrain(label, at: .Leading, to: textField)
view.constrain(textField, at: .Top, to: label, at: .Bottom, diff: 8)
// without MiniLayout:
view.addConstraint( NSLayoutConstraint(item: label, attribute: .Leading, relatedBy: Equal, toItem: textField, attribute: .Leading, multiplier: 1, constant: 0) )
view.addConstraint( NSLayoutConstraint(item: textField, attribute: .Top, relatedBy: Equal, toItem: label, attribute: .Bottom, multiplier: 1, constant: 8) )
Add button
at the center of view
// using MiniLayout:
view.addConstrainedSubview(button, constrain: .CenterX, .CenterY)
// without MiniLayout:
view.addSubview(button)
button.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addConstraint( NSLayoutConstraint(item: button, attribute: .CenterX, relatedBy: Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0) )
view.addConstraint( NSLayoutConstraint(item: button, attribute: .CenterY, relatedBy: Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: 0) )
MiniLayout uses the same enums and the same logic as AutoLayout, there’s nothing new to learn. It just makes the code shorter and more readable.