2️⃣SnapKit

Fall 2023 | Vin Bui

Tired of having to type the extremely long code for setting up auto-layout with NSLayout? SnapKit is here to make our lives easier! SnapKit is a wrapper library that makes setting constraints with auto-layout very simple.

Installation

You can use either Swift Package Manager or CocoaPods to install SnapKit. If using CocoaPods, simply write pod SnapKit in our Podfile then use pod install.

Using SnapKit

The best way to understand how to use SnapKit is to compare it with the code that we have written so far.

// NSLayout
NSLayoutConstraint.activate([
    child.leadingAnchor.constraint(equalTo: parent.leadingAnchor),
    child.topAnchor.constraint(equalTo: parent.topAnchor),
    child.trailingAnchor.constraint(equalTo: parent.trailingAnchor),
    child.bottomAnchor.constraint(equalTo: parent.bottomAnchor)
])

// SnapKit (note that we do not need commas)
child.snp.makeConstraints { make in
    make.leading.equalToSuperview()
    make.top.equalToSuperview()
    make.trailing.equalToSuperview()
    make.bottom.equalToSuperview()
}

// Or we can do the following
child.snp.makeConstraints { make in
    make.leading.top.trailing.bottom.equalToSuperview()
}

// Or even the following
child.snp.makeConstraints { make in
    make.edges.equalToSuperview()
}
// NSLayout with insets, height/width, and relative to other subviews
NSLayoutConstraint.activate([
    childTwo.leadingAnchor.constraint(equalTo: childOne.trailingAnchor, padding: 16),
    childTwo.trailingAnchor.constraint(equalTo: parent.trailingAnchor, padding: -16),
    childTwo.centerYAnchor.constraint(equalTo: childOne.centerYAnchor),
    childTwo.heightAnchor.constraing(equalToConstant: 96)
])

// SnapKit Version
childTwo.snp.makeConstraints { make in
    make.leading.equalTo(childOne.snp.trailing).offset(16)
    make.trailing.equalToSuperview().offset(-16) // or .inset(16)
    make.centerY.equalToSuperview()
    make.height.equalTo(96)
}
// Using SafeAreaLayoutGuide
make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)

SnapKit offers a lot more than just these basic constraints so feel free to Google! We also do not have to set translatesAutoresizingMaskIntoConstraints to false when using SnapKit!

Last updated