Swift 自动布局框架-SnapKit
官方网址: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:
$ gem install cocoapods
To integrate SnapKit into your Xcode project using CocoaPods, specify it in your Podfile:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'SnapKit', '~> 0.15.0'
Then, run the following command:
$ 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:
$ brew update
$ brew install carthage
To integrate SnapKit into your Xcode project using Carthage, specify it in your Cartfile:
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:
$ git submodule add https://github.com/SnapKit/SnapKit.git
- Open the
SnapKitfolder, and dragSnapKit.xcodeprojinto 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.frameworkmatches 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.
let box = UIView()
superview.addSubview(box)
box.snp_makeConstraints { (make) -> Void in
make.top.equalTo(superview).offset(20)
make.left.equalTo(superview).offset(20)
make.bottom.equalTo(superview).offset(-20)
make.right.equalTo(superview).offset(-20)
}
Or even shorter:
let box = UIView()
superview.addSubview(box)
box.snp_makeConstraints { (make) -> Void in
make.edges.equalTo(superview).inset(UIEdgeInsetsMake(20, 20, 20, 20))
}
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
.equalToequivalent to NSLayoutRelation.Equal
.lessThanOrEqualToequivalent to NSLayoutRelation.LessThanOrEqual
.greaterThanOrEqualToequivalent to NSLayoutRelation.GreaterThanOrEqual
These three equality constraints accept one argument which can be any of the following:
1. ViewAttribute
make.centerX.lessThanOrEqualTo(view2.snp_left)
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
// these two constraints are exactly the same
make.left.greaterThanOrEqualTo(label)
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:
// width >= 200 && width <= 400
make.width.greaterThanOrEqualTo(200)
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:
// creates view.left <= view.superview.left + 10
make.left.lessThanOrEqualTo(10)
You can also use other primitives and structs to build your constraints, like so:
make.top.equalTo(42)
make.height.equalTo(20)
make.size.equalTo(CGSizeMake(50, 100))
make.edges.equalTo(UIEdgeInsetsMake(10, 0, 10, 0))
make.left.equalTo(view).offset(UIEdgeInsetsMake(10, 0, 10, 0))
Learn to prioritize
.prorityallows you to specify an exact priority
.priorityHighequivalent to UILayoutPriority.DefaultHigh
.priorityMediumis half way between high and low
.priorityLowequivalent to UILayoutPriority.DefaultLow
Priorities are can be tacked on to the end of a constraint chain like so:
make.left.greaterThanOrEqualTo(label.snp_left).priorityLow()
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
// make top, left, bottom, right equal view2
make.edges.equalTo(view2); // make top = superview.top + 5, left = superview.left + 10,
// bottom = superview.bottom - 15, right = superview.right - 20
make.edges.equalTo(superview).inset(UIEdgeInsetsMake(5, 10, 15, 20))
size
// make width and height greater than or equal to titleLabel
make.size.greaterThanOrEqualTo(titleLabel) // make width = superview.width + 100, height = superview.height - 50
make.size.equalTo(superview).offset(CGSizeMake(100, -50))
center
// make centerX and centerY = button1
make.center.equalTo(button1) // make centerX = superview.centerX - 5, centerY = superview.centerY + 10
make.center.equalTo(superview).offset(CGPointMake(-5, 10))
You can chain view attributes for increased readability:
// All edges but the top should equal those of the superview
make.left.right.bottom.equalTo(superview)
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.
var topConstraint: Constraint? = nil ... // when making constraints
view1.snp_makeConstraints { (make) -> Void in
self.topConstraint = make.top.equalTo(superview).offset(padding.top).constraint
make.left.equalTo(superview).offset(padding.left)
} ...
// then later you can call
self.topConstraint.uninstall() // or if you want to update the constraint
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
// this is Apple's recommended place for adding/updating constraints
// this method can get called multiple times in response to setNeedsUpdateConstraints
// which can be called by UIKit internally or in your code if you need to trigger an update to your constraints
override func updateConstraints() {
self.growingButton.snp_updateConstraints { (make) -> Void in
make.center.equalTo(self);
make.width.equalTo(self.buttonSize.width).priorityLow()
make.height.equalTo(self.buttonSize.height).priorityLow()
make.width.lessThanOrEqualTo(self)
make.height.lessThanOrEqualTo(self)
} // according to apple super should be called at end of method
super.updateConstraints()
}
3. snp_remakeConstraints
snp_remakeConstraints is similar to snp_makeConstraints, but will first remove all existing constraints installed by SnapKit.
func changeButtonPosition() {
self.button.snp_remakeConstraints { (make) -> Void in
make.size.equalTo(self.buttonSize)
if topLeft {
make.top.left.equalTo(10)
} else {
make.bottom.equalTo(self.view).offset(-10)
make.right.equalTo(self.view).offset(-10)
}
}
}
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的更多相关文章
- swift约束框架SnapKit使用
一.Swift - 自动布局库SnapKit的使用详解1(配置.使用方法.样例) 为了适应各种屏幕尺寸,iOS 6后引入了自动布局(Auto Layout)的概念,通过使用各种 Constrain ...
- Swift - 自动布局库SnapKit的使用详解4(样例1:实现一个登录页面)
前面的几篇文章讲解了自动布局库SnapKit的使用方法.本文通过一个完整的样例(登录页面)来演示在实际项目中如何使用SnapKit来实现自动化布局的.1,效果图如下
- Swift - 自动布局库SnapKit的使用详解1(配置、使用方法、样例)
为了适应各种屏幕尺寸,iOS 6后引入了自动布局(Auto Layout)的概念,通过使用各种 Constraint(约束)来实现页面自适应弹性布局. 在 StoryBoard 中使用约束实现自动布局 ...
- Swift - 自动布局库SnapKit的使用详解3(约束优先级,约束做动画)
1,约束优先级我们使用SnapKit的时候,还可以定义约束的优先级.这样当约束出现冲突的时候,优先级高的约束覆盖优先级低的约束.具体优先级可以放在约束链的结束处. (1)可以设置如下几种优先级 pri ...
- Swift - 自动布局库SnapKit的使用详解2(约束的更新、移除、重做)
在之前的文章中我介绍了如何使用SnapKit的 snp_makeConstraints 方法进行各种约束的设置.但有时我们的页面并不是一直固定不变的,这就需要修改已经存在的约束.本文介绍如何更新.移除 ...
- iOS 自动布局框架 – Masonry 详解
目前iOS开发中大多数页面都已经开始使用Interface Builder的方式进行UI开发了,但是在一些变化比较复杂的页面,还是需要通过代码来进行UI开发的.而且有很多比较老的项目,本身就还在采用纯 ...
- iOS自动布局框架-Masonry详解
首先,在正式使用Masonry之前,我们先来看看在xib中我们是如何使用AutoLayout 从图中我们可以看出,只要设置相应得局限,控制好父视图与子视图之间的关系就应该很ok的拖出你需要的需 ...
- Swift - 开源框架总结
苹果官方Swift文档<The Swift Programming Language> 苹果开发者Swift文档及介绍 网友整理的Swift中文文档< Apple Swift编程语言 ...
- ElegantSnap 一个优雅的,易用的iOS/tvOS/macOS自动布局框架, 超级详细的使用教程,多视图水平等宽/垂直等高排列
ElegantSnap ElegantSnap(Base on SnapKit) to make Auto Layout easy and elegant on both iOS and OS X. ...
随机推荐
- Google的Bigtable学习笔记(不保证正确性)
跪求各路大侠指正:1.首先是一个列式存储的简单数据模型的数据库,它比键值对模型/文档模型NoSQL数据库复杂点(也就更强一点).2.它的分布式存储性能依靠于GFS也就对单机房网络有硬性指标.3.它同时 ...
- Linux下oracle11gR2系统安装到数据库建立配置及最后oracle的dmp文件导入一站式操作记录
简介 之前也在linux下安装过oralce,可每次都是迷迷糊糊的,因为大脑一片空白,网上随便看见一个文档就直接复制,最后搞了乱七八糟,虽然装上了,却乱得很,现在记录下来,希望能给其他网上朋友遇到问题 ...
- 微软今日发布汇总:VS2015, .NET 4.6, C# 6.0, F# 4.0等重量级产品正式上线
Visual Studio Visual Studio 2015 下载 VS2015新功能列表 ‘ Visual Studio 2013 更新包 5.0 下载 其中包含Visual Studio 20 ...
- 使用ConditionalScope进行高效的SharePoint CSOM编程
在上一篇文章中讲述了 ExceptionHandlingScope的使用后,本章主要讲述ConditionalScope的用法. ConditionalScope在设计思路和解决问题上同Excepti ...
- .net中对象序列化技术浅谈
.net中对象序列化技术浅谈 2009-03-11 阅读2756评论2 序列化是将对象状态转换为可保持或传输的格式的过程.与序列化相对的是反序列化,它将流转换为对象.这两个过程结合起来,可以轻松地存储 ...
- Atitit.常用的gc算法
Atitit.常用的gc算法 1.1. 记-清除算法1 1.2. 复制算法1 1.3. 标记-整理算法2 1.4. 分代收集算法2 1.1. 记-清除算法 最基础的收集算法,算法分为标记和清除两个阶段 ...
- 祸福相依,大难之后的O2O迎来新福报?
今天的O2O似乎已经成为了一个人人都不愿意提的名词,很多原本做O2O的创业者,如今都不提自己是O2O,只说是互联网+.创业者们实际上仍然是在干着O2O的事情,之所以不敢提不愿提,无非就是一提O2O,投 ...
- Apple移动设备处理器指令集 armv6、armv7、armv7s及arm64
Arm处理器,因为其低功耗和小尺寸而闻名,几乎所有的手机处理器都基于arm,其在嵌入式系统中的应用非常广泛,它的性能在同等功耗产品中也很出色. Armv6.armv7.armv7s.arm64都是ar ...
- 匿名管道读取CMD回显信息
之前用了很坑爹的做法去读取了cmd命令的回显信息,现在发现了用匿名管道的实现方法,由于楼主没有学过Windows核心编程,找了一个代码来凑数 存下来以后研究 #include <windows. ...
- android 多布局
做为最后的方法,也是最后一个才会考虑的方法,那就是为不同的尺寸界面单独写布局.不到万不得已不要用这个方法,相信不少人和我一样都被逼着用过这个方法吧.需要说明的是,横竖屏切换使用不同布局也是用这个方法解 ...