Github
官方文档
安装SnapKit
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!
target '<Your Target Name>' do
pod 'SnapKit', '~> 3.2.0'
end
入门示例
import UIKit
import SnapKit
class ViewController: UIViewController {
lazy var box = UIView()
override func viewDidLoad() {
super.viewDidLoad()
//在屏幕中间设置个110正方形
box.backgroundColor = UIColor.green
self.view.addSubview(box)
box.snp.makeConstraints{ (make) -> Void in
make.width.height.equalTo(110)
make.center.equalTo(self.view)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
NSLayoutAttributeCenterX 视图的中点的X值
NSLayoutAttributeCenterY 视图中点的Y值
NSLayoutAttributeBaseline 视图的基准线
- 修正约束语法:
.equalTo:等于
.lessThanOrEqualTo:小于等于
.greaterThanOrEqualTo:大于等于
- 倍率修正, 使用multipliedBy实例:
override func viewDidLoad() {
super.viewDidLoad()
var box = UIView()
box.backgroundColor = UIColor.green
self.view.addSubview(box)
box.snp.makeConstraints{ (make) -> Void in
make.width.height.equalTo(110)
make.center.equalTo(self.view)
}
var two = UILabel()
two.backgroundColor = UIColor.yellow
self.view.addSubview(two)
//使two控件为box控件的0.3倍大小
two.snp.makeConstraints{ (make) in
make.center.equalTo(box)
make.size.equalTo(box).multipliedBy(0.3)
}
}
actionBut.snp.makeConstraints{ (make) in
//actionBut 与orangeBox偏移30 make.top.equalTo(orangeBox.snp.bottom).offset(30)
make.width.equalTo(220)
make.height.equalTo(35)
make.centerX.equalTo(self.view)
}