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)])