官方网址:http://snapkit.io/

Github: https://github.com/SnapKit/SnapKit

SnapKit is a DSL to make Auto Layout easy on both iOS and OS X.

  • Simple & Expressive chaining DSL allows building constraints with minimal amounts of code while ensuring they are easy to read and understand.
  • Type Safe by design to reduce programmer error and keep invalid constraints from being created in the first place for maximized productivity.
  • Compatible for both iOS and OS X apps installable through Cocoapods or Carthage.
  • Free to use in all projects and licensed under the flexible MIT license.

Requirements

  • iOS 7.0+ / OS X 10.9+
  • Swift 2.0
  • Xcode 7.0+

While SnapKit supports iOS 7.0 and OS X 10.9 these are considered legacy platforms, so you must manually integrate the source files directly. Please see the Legacy Platforms page for more information and steps.

Installing

The first thing you’ll need to do with SnapKit is get it installed into your project. We support three different integrations:

Cocoapods

CocoaPods is a dependency manager for Cocoa projects.

CocoaPods 0.36 adds supports for Swift and embedded frameworks. You can install it with the following command:

  1. $ gem install cocoapods

To integrate SnapKit into your Xcode project using CocoaPods, specify it in your Podfile:

  1. source 'https://github.com/CocoaPods/Specs.git'
  2. platform :ios, '8.0'
  3. use_frameworks!
  4. pod 'SnapKit', '~> 0.15.0'

Then, run the following command:

  1. $ pod install

Carthage

Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.

You can install Carthage with Homebrew using the following command:

  1. $ brew update
  2. $ brew install carthage

To integrate SnapKit into your Xcode project using Carthage, specify it in your Cartfile:

  1. github "SnapKit/SnapKit" >= 0.15.0

Embedded Framework

  • Add SnapKit as a submodule by opening the Terminal, cd-ing into your top-level project directory, and entering the following command:
  1. $ git submodule add https://github.com/SnapKit/SnapKit.git
  • Open the SnapKit folder, and drag SnapKit.xcodeproj into the file navigator of your app project.
  • In Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the "Targets" heading in the sidebar.
  • Ensure that the deployment target of SnapKit.framework matches that of the application target.
  • In the tab bar at the top of that window, open the "Build Phases" panel.
  • Expand the "Target Dependencies" group, and add SnapKit.framework.
  • Click on the + button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and addSnapKit.framework.

Usage

SnapKit is designed to be extremely easy to use. Let's say we want to layout a box that is constrained to it's superview's edges with 20pts of padding.

  1. let box = UIView()
  2. superview.addSubview(box)
  3. box.snp_makeConstraints { (make) -> Void in
  4. make.top.equalTo(superview).offset(20)
  5. make.left.equalTo(superview).offset(20)
  6. make.bottom.equalTo(superview).offset(-20)
  7. make.right.equalTo(superview).offset(-20)
  8. }

Or even shorter:

  1. let box = UIView()
  2. superview.addSubview(box)
  3. box.snp_makeConstraints { (make) -> Void in
  4. make.edges.equalTo(superview).inset(UIEdgeInsetsMake(20, 20, 20, 20))
  5. }

Not only does this greatly shorten and increase the readability of constraints SnapKit is also taking care of a few crucial steps in the process:

  • Determining the best common superview to install the constraints on.
  • Keeping track of the constrainted installed so they can easily be removed later.
  • Ensuring setTranslatesAutoresizingMaskIntoConstraints(false) is called on all appropriate views.

Not all things are created equal

.equalTo equivalent to NSLayoutRelation.Equal

.lessThanOrEqualTo equivalent to NSLayoutRelation.LessThanOrEqual

.greaterThanOrEqualTo equivalent to NSLayoutRelation.GreaterThanOrEqual

These three equality constraints accept one argument which can be any of the following:

1. ViewAttribute

  1. make.centerX.lessThanOrEqualTo(view2.snp_left) 
  1. make.centerX.lessThanOrEqualTo(view2.snp_left)
ViewAttribute NSLayoutAttribute
view.snp_left NSLayoutAttribute.Left
view.snp_right NSLayoutAttribute.Right
view.snp_top NSLayoutAttribute.Top
view.snp_bottom NSLayoutAttribute.Bottom
view.snp_leading NSLayoutAttribute.Leading
view.snp_trailing NSLayoutAttribute.Trailing
view.snp_width NSLayoutAttribute.Width
view.snp_height NSLayoutAttribute.Height
view.snp_centerX NSLayoutAttribute.CenterX
view.snp_centerY NSLayoutAttribute.CenterY
view.snp_baseline NSLayoutAttribute.Baseline

if you want view.left to be greater than or equal to label.left:2. UIView/NSView

  1. // these two constraints are exactly the same
  2. make.left.greaterThanOrEqualTo(label)
  3. make.left.greaterThanOrEqualTo(label.snp_left)

  

3. Strict Checks

Auto Layout allows width and height to be set to constant values. if you want to set view to have a minimum and maximum width you could pass a primitive to the equality blocks:

  1. // width >= 200 && width <= 400
  2. make.width.greaterThanOrEqualTo(200)
  3. make.width.lessThanOrEqualTo(400)

  

However Auto Layout does not allow alignment attributes such as left, right, centerY etc to be set to constant values. So if you pass a primitive for these attributes SnapKit will turn these into constraints relative to the view's superview ie:

  1. // creates view.left <= view.superview.left + 10
  2. make.left.lessThanOrEqualTo(10)

  

You can also use other primitives and structs to build your constraints, like so:

  1. make.top.equalTo(42)
  2. make.height.equalTo(20)
  3. make.size.equalTo(CGSizeMake(50, 100))
  4. make.edges.equalTo(UIEdgeInsetsMake(10, 0, 10, 0))
  5. make.left.equalTo(view).offset(UIEdgeInsetsMake(10, 0, 10, 0))

  

Learn to prioritize

.prority allows you to specify an exact priority

.priorityHigh equivalent to UILayoutPriority.DefaultHigh

.priorityMedium is half way between high and low

.priorityLow equivalent to UILayoutPriority.DefaultLow

Priorities are can be tacked on to the end of a constraint chain like so:

  1. make.left.greaterThanOrEqualTo(label.snp_left).priorityLow()
  2. make.top.equalTo(label.snp_top).priority(600)

  

Composition, composition, composition

SnapKit also gives you a few convenience methods to create multiple constraints at the same time.

edges

  1. // make top, left, bottom, right equal view2
  2. make.edges.equalTo(view2);
  3.  
  4. // make top = superview.top + 5, left = superview.left + 10,
  5. // bottom = superview.bottom - 15, right = superview.right - 20
  6. make.edges.equalTo(superview).inset(UIEdgeInsetsMake(5, 10, 15, 20))

  

size

  1. // make width and height greater than or equal to titleLabel
  2. make.size.greaterThanOrEqualTo(titleLabel)
  3.  
  4. // make width = superview.width + 100, height = superview.height - 50
  5. make.size.equalTo(superview).offset(CGSizeMake(100, -50))

  

center

  1. // make centerX and centerY = button1
  2. make.center.equalTo(button1)
  3.  
  4. // make centerX = superview.centerX - 5, centerY = superview.centerY + 10
  5. make.center.equalTo(superview).offset(CGPointMake(-5, 10))

  

You can chain view attributes for increased readability:

  1. // All edges but the top should equal those of the superview
  2. make.left.right.bottom.equalTo(superview)
  3. make.top.equalTo(otherView)

  

Hold on for dear life

Sometimes you need modify existing constraints in order to animate or remove/replace constraints. In SnapKit there are a few different approaches to updating constraints.

1. References

You can hold on to a reference of a particular constraint by assigning the result of a constraint make expression to a local variable or a class property. You could also reference multiple constraints by storing them away in an array.

  1. var topConstraint: Constraint? = nil
  2.  
  3. ...
  4.  
  5. // when making constraints
  6. view1.snp_makeConstraints { (make) -> Void in
  7. self.topConstraint = make.top.equalTo(superview).offset(padding.top).constraint
  8. make.left.equalTo(superview).offset(padding.left)
  9. }
  10.  
  11. ...
  12. // then later you can call
  13. self.topConstraint.uninstall()
  14.  
  15. // or if you want to update the constraint
  16. self.topConstraint.updateOffset(5)

  

2. snp_updateConstraints

Alternative if you are only updating the constant value of the constraint you can use the methodsnp_updateConstraints instead of snp_makeConstraints

  1. // this is Apple's recommended place for adding/updating constraints
  2. // this method can get called multiple times in response to setNeedsUpdateConstraints
  3. // which can be called by UIKit internally or in your code if you need to trigger an update to your constraints
  4. override func updateConstraints() {
  5. self.growingButton.snp_updateConstraints { (make) -> Void in
  6. make.center.equalTo(self);
  7. make.width.equalTo(self.buttonSize.width).priorityLow()
  8. make.height.equalTo(self.buttonSize.height).priorityLow()
  9. make.width.lessThanOrEqualTo(self)
  10. make.height.lessThanOrEqualTo(self)
  11. }
  12.  
  13. // according to apple super should be called at end of method
  14. super.updateConstraints()
  15. }

  

  1. 3. snp_remakeConstraints

snp_remakeConstraints is similar to snp_makeConstraints, but will first remove all existing constraints installed by SnapKit.

  1. func changeButtonPosition() {
  2. self.button.snp_remakeConstraints { (make) -> Void in
  3. make.size.equalTo(self.buttonSize)
  4.  
  5. if topLeft {
  6. make.top.left.equalTo(10)
  7. } else {
  8. make.bottom.equalTo(self.view).offset(-10)
  9. make.right.equalTo(self.view).offset(-10)
  10. }
  11. }
  12. }

  

Features

  • Not limited to a subset of Auto Layout. Anything NSLayoutConstraint can do SnapKit can also do.
  • Better debugging support to help find breaking constraints.
  • No crazy operator overloads.
  • Not string or dictionary based and you get the strictest compile time checks possible.

TODO

  • Example Projects
  • Better Debugging Support

Swift 自动布局框架-SnapKit的更多相关文章

  1. swift约束框架SnapKit使用

    一.Swift - 自动布局库SnapKit的使用详解1(配置.使用方法.样例)   为了适应各种屏幕尺寸,iOS 6后引入了自动布局(Auto Layout)的概念,通过使用各种 Constrain ...

  2. Swift - 自动布局库SnapKit的使用详解4(样例1:实现一个登录页面)

    前面的几篇文章讲解了自动布局库SnapKit的使用方法.本文通过一个完整的样例(登录页面)来演示在实际项目中如何使用SnapKit来实现自动化布局的.1,效果图如下

  3. Swift - 自动布局库SnapKit的使用详解1(配置、使用方法、样例)

    为了适应各种屏幕尺寸,iOS 6后引入了自动布局(Auto Layout)的概念,通过使用各种 Constraint(约束)来实现页面自适应弹性布局. 在 StoryBoard 中使用约束实现自动布局 ...

  4. Swift - 自动布局库SnapKit的使用详解3(约束优先级,约束做动画)

    1,约束优先级我们使用SnapKit的时候,还可以定义约束的优先级.这样当约束出现冲突的时候,优先级高的约束覆盖优先级低的约束.具体优先级可以放在约束链的结束处. (1)可以设置如下几种优先级 pri ...

  5. Swift - 自动布局库SnapKit的使用详解2(约束的更新、移除、重做)

    在之前的文章中我介绍了如何使用SnapKit的 snp_makeConstraints 方法进行各种约束的设置.但有时我们的页面并不是一直固定不变的,这就需要修改已经存在的约束.本文介绍如何更新.移除 ...

  6. iOS 自动布局框架 – Masonry 详解

    目前iOS开发中大多数页面都已经开始使用Interface Builder的方式进行UI开发了,但是在一些变化比较复杂的页面,还是需要通过代码来进行UI开发的.而且有很多比较老的项目,本身就还在采用纯 ...

  7. iOS自动布局框架-Masonry详解

    首先,在正式使用Masonry之前,我们先来看看在xib中我们是如何使用AutoLayout     从图中我们可以看出,只要设置相应得局限,控制好父视图与子视图之间的关系就应该很ok的拖出你需要的需 ...

  8. Swift - 开源框架总结

    苹果官方Swift文档<The Swift Programming Language> 苹果开发者Swift文档及介绍 网友整理的Swift中文文档< Apple Swift编程语言 ...

  9. ElegantSnap 一个优雅的,易用的iOS/tvOS/macOS自动布局框架, 超级详细的使用教程,多视图水平等宽/垂直等高排列

    ElegantSnap ElegantSnap(Base on SnapKit) to make Auto Layout easy and elegant on both iOS and OS X. ...

随机推荐

  1. Spring.Net+Nhibernate

    Spring.net+Nhibernate系列优秀文章导航 冬哥的Spring.Net+Nhibernate Spring.Net+NHibenate+Asp.Net mvc +ExtJs 系列 NH ...

  2. 配置ubuntu 16.04.1 LTS odoo 10.0开发环境

    使用VMware Fusion 8.5.0创建ubuntu 64bit虚拟机:使用ubuntu-16.04.1-desktop-amd64.iso镜像缺省安装ubuntu,用户名odoo,密码1234 ...

  3. python chardet简单应用

    python的字符串编码识别模块(第三方库): 官方地址: http://pypi.python.org/pypi/chardet   import chardet import urllib   # ...

  4. 真实世界:使用WCF扩展在方法调用前初始化环境

    OperationInvoker 介绍 OperationInvoker 是 WCF 运行时模型中在调用最终用户代码前的最后一个扩展点,OperationInvoker 负责最终调用 Service ...

  5. [JAVA] java仿windows 字体设置选项卡

    想用java做一个像windows里一样的txt编辑软件,涉及到字体设置选项卡,在网上找了很久都没找到,就生气啦自己写一个,现在贴这里分享一下,下次再遇到这样的问题就不用自己亲自打代码啦! packa ...

  6. 【点滴javascript】变量与作用域

    基本类型与引用类型 ECMAScript的的变量有两种类型: 基本类型(值类型):简单数据段 引用类型:多个值构成的对象 在变量赋值结束后,解析器必须知道这个变量时基本数据类型还是引用类型,需要注意的 ...

  7. Fiddler初探

    我们知道监视Http和Https请求的工具有多种,例如:HttpWatch,FireBug等.但是今天接触到一种新的工具Fiddler.Fiddler能记录所有客户端和服务器的http和https请求 ...

  8. paip.python NameError name 'xxx' is not defined\

    paip.python NameError name 'xxx' is not defined\ 导入一个另一个文件里面的函数的时候儿,出孪这个err #这个仅仅导入孪file...要使用里面的fun ...

  9. MapReduce之单词计数

    最近在看google那篇经典的MapReduce论文,中文版可以参考孟岩推荐的 mapreduce 中文版 中文翻译 论文中提到,MapReduce的编程模型就是: 计算利用一个输入key/value ...

  10. Leetcode-121 Best Time to Buy and Sell Stock

    #121   Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price ...