Episode #233

SnapKit

18 minutes
Published on August 25, 2016

This video is only available to subscribers. Get access to this video and 582 others.

Writing Autolayout constraints from code can be quite tedious. SnapKit, the Swift-friendly successor to Masonry, is a friendly DSL that allows creating and updating constraints easy and readable. In this episode we use SnapKit to build out a simple interface mockup using Autolayout completely in code.

Episode Links

Installing SnapKit

Using CocoaPods, add the SnapKit pod to your Podfile:

pod 'SnapKit'

Then run pod install to install it.

Making constraints

Making constraints for a view starts with the snp_makeConstraints method. The method takes a closure, and yields a ConstraintMaker to it. Typically, we name this parameter make:

let header = UIView()
header.backgroundColor = UIColor(white: 0.9, alpha: 1)
view.addSubview(header)
header.snp_makeConstraints { make in
   ...
}

Note that we don't need to set translatesAutoResizingMaskIntoConstraints = false, as this is handled for us by SnapKit. Inside the block we can make constraints by using the DSL provided by the make parameter:

make.left.equalTo(view.snp_left)
make.right.equalTo(view.snp_right)
make.top.equalTo(view.snp_top)
make.height.equalTo(64)

When constraining to dimensions directly from a view, make sure to use the snp_ prefixed properties.

Updating Constraints

Often we need to update constraints in order to make room for new views, or to animate something to a new size or location. Traditionally this means keeping a reference to a constraint so you can update it later.

With SnapKit, you can simple call snp_updateConstraints and any matching constraint will get remove and readded, providing the same effect but without needing to keep a reference of the constraint around.

button.snp_updateConstraints { update in
    update.width.equalTo(44)
}

This episode uses Snapkit 0.22.0, Cocoapods 1.0.1.