swift相关的教程还是太少,很多东西都靠自己琢磨。今天研究了一下别人oc实现的autolayout,写篇笔记。
首先是正常的创建元素,为了熟悉实现的方式,我在学习过程中是完全放弃storyboard的。
- var v1 = UILabel()
- v1.backgroundColor = UIColor.redColor()
- v1.text = "v1"
- v1.setTranslatesAutoresizingMaskIntoConstraints(false)
- //设置在约束布局系统中是否把自动布局转换为约束布局
- self.view.addSubview(v1)
然后添加约束
- self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
- "H:|-1-[v1]-1-|",
- options: .DirectionLeadingToTrailing,
- metrics: nil,
- views: ["v1":v1]))
constraintsWithVisualFormat:参数为NSString型,指定Contsraint的属性,是垂直方向的限定还是水平方向的限定,参数定义一般如下:
H:Expression 表示水平或者垂直(V)方向上相对于SuperView的位置
options:字典类型的值;这里的值一般在系统定义的一个enum里面选取
metrics:nil;一般为nil ,参数类型为NSDictionary,从外部传入
views:就是上面所加入到NSDictionary中的绑定的元素
表达式规则
|: 表示父视图
-: 表示距离
>= :表示视图间距、宽度和高度必须大于或等于某个值
<= :表示视图间距、宽度和高度必须小宇或等于某个值 == :表示视图间距、宽度或者高度必须等于某个值
比如我们要把上面创建的label设置为距离父视图左右都是10,那么表达式就是
- "H:|-10-[v1]-10-|"
我们要让他高40,距离父视图顶部为10
- "V:|-10-[v1(==40)]"
如果我们再创建V2,V3两个元素,让他们等宽排列在V1的下面
- "H:|-1-[v2(v3)]-[v3]-1-|"
完整的代码就是
- import UIKit
-
- class ViewController: UIViewController {
- override func viewDidLoad() {
- super.viewDidLoad()
-
- var v1 = UILabel()
- v1.backgroundColor = UIColor.redColor()
- v1.setTranslatesAutoresizingMaskIntoConstraints(false)
- v1.textAlignment = NSTextAlignment.Center
- v1.text = "v1"
- self.view.addSubview(v1)
-
- var v2 = UILabel()
- v2.backgroundColor = UIColor.redColor();
- v2.setTranslatesAutoresizingMaskIntoConstraints(false)
- v2.textAlignment = NSTextAlignment.Center
- v2.text = "v2"
- self.view.addSubview(v2)
-
- var v3 = UILabel()
- v3.backgroundColor = UIColor.redColor();
- v3.setTranslatesAutoresizingMaskIntoConstraints(false)
- v3.textAlignment = NSTextAlignment.Center
- v3.text = "v3"
- self.view.addSubview(v3)
-
-
- self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
- "H:|-10-[v1]-10-|",
- options: .DirectionLeadingToTrailing,
- metrics: nil,
- views: ["v1":v1]))
- self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
- "H:|-10-[v2(v3)]-[v3]-10-|",
- options: .DirectionLeadingToTrailing,
- metrics: nil,
- views: ["v2":v2,"v3":v3]))
- self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
- "V:|-20-[v1(==40)]-10-[v2(==40)]",
- options: .DirectionLeadingToTrailing,
- metrics: nil,
- views: ["v1":v1, "v2":v2,"v3":v3]))
- self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
- "V:[v1]-10-[v3(==40)]",
- options: .DirectionLeadingToTrailing,
- metrics: nil,
- views: ["v1":v1, "v3":v3]))
-
-
- }
-
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- // Dispose of any resources that can be recreated.
- }
- }
效果如下图, 无论在什么宽度的设备下面,他们布局保持不变。