Episode #233 | 18 minutes | published on 08/25/2016 | Uses SnapKit-0.22.0, CocoaPods-1.0.1
Subscribers Only
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)
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:


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
blog comments powered by Disqus