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.
// NSLayoutNSLayoutConstraint.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 followingchild.snp.makeConstraints { make in make.leading.top.trailing.bottom.equalToSuperview()}// Or even the followingchild.snp.makeConstraints { make in make.edges.equalToSuperview()}
// NSLayout with insets, height/width, and relative to other subviewsNSLayoutConstraint.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 VersionchildTwo.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 SafeAreaLayoutGuidemake.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!