1、Masoryswift
Masory庫 如今成爲snapKit spa
首先找到SnapKit-develop庫 .net
將其中的source庫導入工程當中 不須要任何配置文件M跟 oc 的使用方法沒有什麼太大的區別,如下爲代碼對象
let view=UIView()ip
view.backgroundColor=UIColor.blueColor()get
view.frame = CGRectMake(0, 0, 40, self.frame.height)it
backView.addSubview(view)
view.snp_makeConstraints { (make) -> Void in
//top
make.bottom.equalTo(backView.snp_bottom).offset(11)
make.top.equalTo(backView.snp_top).offset(-10)
make.left.equalTo(backView.snp_left).offset(8)
make.right.equalTo(backView.snp_right).offset(-8)配置
}autolayout
能夠清楚的看見 與oc的代碼 基本一致 惟一的不一樣 在於swift前置爲snp 而oc得前置爲mas 並且數字能夠直接寫在上 不須要添加@符號 方法
添加高度或者寬度的代碼值
make.width.equalTo(120)
make.height.equalTo(30)
注意的坑:
一、添加約束前 必須有父視圖,不然會進行報錯
二、添加約束必須考慮全面 依靠某一個對象添加約束,那麼這個對象必須是存在的已經創建的,不然則會報錯
三、添加約束的距離值,是左邊的位置減去右邊的位置,因此添加右邊和下邊的約束爲負值
2、autolayout
跟oc的基本相同除了格式的變化 還有參數的變化,
具體代碼以下
let viewq=UIView()
viewq.backgroundColor = UIColor(red: 0.4, green: 0.3, blue: 0.1, alpha: 1)
viewq.layer.cornerRadius=4
viewq.layer.borderWidth = 0.5
viewq.layer.borderColor = UIColor.blackColor().CGColor
self.addSubview(viewq)
//居中====單一的約束
self.addConstraint(NSLayoutConstraint(item: viewq,
attribute:.CenterX,
relatedBy:.Equal,
toItem: self,
attribute: .CenterX,
multiplier: 1,
constant: 0))
//距離底部是高度的20單位=====多條約束
//距離頂部20
self.addConstraints([NSLayoutConstraint(item: viewq,
attribute: .Top,
relatedBy: .Equal,
toItem: self,
attribute: .Top,
multiplier: 1,
constant: 20),
NSLayoutConstraint(item: viewq,
attribute:.Bottom,
relatedBy: .Equal,
toItem: self,
attribute: .Bottom,
multiplier: 1,
constant:-20)])