Swift学习:VFL约束语言的学习

继续学习AutoLayout的约束,发现约束不止可以使用这样的写法

NSLayoutConstraint(item: , attribute: , relatedBy: , toItem: , attribute: , multiplier: , constant: )

还可以使用VFL的语言

虽然看起来难,不过明白后反而会觉得还是非常好用的!

VFL(Visual Format Language)

首先:swift中的API

NSLayoutConstraint.constraints(withVisualFormat: , options: , metrics: <[String : Any]?>, views: <[String : Any]>)

**
* withVisualFormat:VFl语句
* options:对齐方式
* metrics:传入一个字典 ,VFL中的key对应的值
* views:传入一个字典,VFL中key对应的View
**
举个栗子
let buttonConstraintV = NSLayoutConstraint.constraints(withVisualFormat: "V:|-100-[button(30)]", options: .directionMask, metrics: nil, views: ["button":alertTestButton])
alertTestButton.superview?.addConstraints(buttonConstraintV)

let buttonConstraintH = NSLayoutConstraint.constraints(withVisualFormat: "H:|-100-[button]-100-|", options: .directionMask, metrics: nil, views: ["button":alertTestButton])
alertTestButton.superview?.addConstraints(buttonConstraintH)

let buttonConstraintH = NSLayoutConstraint.constraints(withVisualFormat: "H:|-m-[button]-m-|", options: .directionMask, metrics: ["m":100], views: ["button":alertTestButton])
alertTestButton.superview?.addConstraints(buttonConstraintH)

V:代表垂直方向
H:代表水平方向

|: 表示父View的边界
-: 表示间隔
|-10-[button] :表示button距离边界为10

V:|-100-[button(30)] :表示垂直方向上button距离上方边界的距离为100 , button的高度为30

V:|-100-[button(text)] :表示垂直方向上button距离上方边界的距离为100 , button的高度 与text等高

H:|-100-[button]-100-|:表示水平方向上button距离左边界100,距离右边界100

H:|-m-[button]-m-|:表示水平方向上button距离左边界m,距离右边界m(可以用来动态改变值)

H:[button1][button2]:表示水平方向上button1后面紧跟button2
H:[button1]-10-[button2]:表示水平方向上button1距离为10后面跟着button2

m值以[key:value]字典的方式设为metrics参数(数值)
button值[key:value]字典的方式设为views参数(view)

VFL虽然很好用但是有些比较复杂的布局貌似还是得用之前学过的
Swift学习:约束的基本使用 来完成

嗯 大概就是这样,如果发现错误或者有什么问题还请留言指出,大家共同学习进步,谢谢

你可能感兴趣的:(Swift学习:VFL约束语言的学习)