Some time ago I mentioned the objective-c library Masonry that dramatically simplifies programming AutoLayout making your code more concise and readable.
Here’s an open source library called Snap which provides a Swift based implementation of the objective-c Masonry library.
Snap provides its own DSL dramatically reducing the amount of code required to use the Auto Layout API.
This simple example from the readme shows how much code is required to use NSLayoutConstraints to have a view fill its superview inset 10 pixels on each side:
let view1 = UIView()
view1.setTranslatesAutoresizingMaskIntoConstraints(false)
view1.backgroundColor = UIColor.greenColor()
superview.addSubview(view1)
let padding = UIEdgeInsetsMake(10, 10, 10, 10)
superview.addConstraints([
NSLayoutConstraint(
item: view1,
attribute: NSLayoutAttribute.Top,
relatedBy: NSLayoutRelation.Equal,
toItem: superview,
attribute: NSLayoutAttribute.Top,
multiplier: 1.0,
constant: padding.top
),
NSLayoutConstraint(
item: view1,
attribute: NSLayoutAttribute.Left,
relatedBy: NSLayoutRelation.Equal,
toItem: superview,
attribute: NSLayoutAttribute.Left,
multiplier: 1.0,
constant: padding.left
),
NSLayoutConstraint(
item: view1,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: superview,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1.0,
constant: -padding.bottom
),
NSLayoutConstraint(
item: view1,
attribute: NSLayoutAttribute.Right,
relatedBy: NSLayoutRelation.Equal,
toItem: superview,
attribute: NSLayoutAttribute.Right,
multiplier: 1.0,
constant: -padding.right
)
])
And using Snap this could be as short as:
view1.snp_makeConstraints { make in
make.edges.equalTo(superview).with.insets(padding)
return // this return is a fix for implicit returns in Swift and is only required for single line constraints
}
You can find Snap on Github here.
A nice Swift based library for working with Auto Layout.
Original article: Open Source Swift Library That Greatly Simplifies Working With Auto Layout
©2015 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.