What is SnapKit and why is it needed?
SnapKit is a powerful and elegant DSL (Domain-Specific Language) library for working with Auto Layout in iOS, macOS, tvOS, and watchOS applications written in Swift. If you have ever written constraints manually using the standard Apple API, you know how verbose and hard to read it can be. SnapKit solves this problem by providing a clean, intuitive syntax that makes layout code read like plain English.
Why is SnapKit needed?
- Code readability: Instead of long chains of
NSLayoutConstraint(item:attribute:relatedBy:toItem:attribute:multiplier:constant:)calls, you writeview.snp.makeConstraints { $0.center.equalToSuperview() }. - Development speed: Layout becomes faster because the code is shorter and easier to understand.
- Type safety: SnapKit uses Swift's strong typing, reducing the likelihood of runtime errors.
- Flexibility: Supports all Auto Layout features: priorities, aspect ratios, updating and overriding constraints.
- Active community: The library is widely used in the industry, has excellent documentation, and a large number of examples.
Installing SnapKit
SnapKit can be installed using one of the popular dependency managers for Swift. Below are instructions for Swift Package Manager (SPM) and CocoaPods.
1. Swift Package Manager (recommended method)
SPM is a package manager built into Xcode. It is the simplest and most modern way.
- In Xcode, open your project.
- Go to File → Add Packages...
- In the search field, enter the SnapKit repository URL:
https://github.com/SnapKit/SnapKit.git - Select the desired version (latest stable is recommended) and click Add Package.
- Ensure the package is added to your target.
2. CocoaPods
If you use CocoaPods, add the following line to your Podfile:
platform :ios, '12.0'use_frameworks!
target 'YourAppTarget' do pod 'SnapKit', '~> 5.6.0'endThen run the command pod install in the terminal in your project folder.
3. Carthage (less popular)
Add to Cartfile:
github "SnapKit/SnapKit" ~> 5.6.0Run carthage update and add the framework to your project.
Quick Start with Code Example
Let's create a simple screen with a red square centered on the screen. This is the classic "Hello, World!" for layout.
import UIKitimport SnapKit
class ViewController: UIViewController {
override func viewDidLoad() { super.viewDidLoad() setupUI() }
private func setupUI() { // 1. Create the view let redView = UIView() redView.backgroundColor = .red view.addSubview(redView)
// 2. Apply SnapKit for layout redView.snp.makeConstraints { make in make.center.equalToSuperview() // Center relative to parent make.width.height.equalTo(100) // Width and height = 100 } }}What is happening here?
redView.snp.makeConstraints— this is the entry point to the SnapKit DSL.snpis a special property that SnapKit adds to all UIView instances.- Inside the closure, we get the
makeobject (ConstraintMaker), with which we describe the constraints. make.center.equalToSuperview()— centers the view relative to its superview.