NSLayoutConstraint(VFL)简单使用

定义

1
2
3
var aView: UIView!
var imgView: UIImageView!
var lab: UILabel!

创建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
aView = UIView(frame: CGRectMake(10,70,300,200))
self.view.addSubview(aView)

imgView = UIImageView()
imgView.image = UIImage(named: "img")

lab = UILabel()
lab.text = "this is a UILabel"

aView.addSubview(imgView)
aView.addSubview(lab)

aView.layer.borderWidth = 1
imgView.layer.borderWidth = 1
lab.layer.borderWidth = 1

约束

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//VFL全称是Visual Format Language,翻译过来是“可视化格式语言”。
//
// H:[cancelButton(72)]-12-[acceptButton(50)]
// canelButton宽72,acceptButton宽50,它们之间间距12
//
// H:[wideView(>=60@700)]
// wideView宽度大于等于60point,该约束条件优先级为700(优先级最大值为1000,优先级越高的约束越先被满足)
//
// V:[redBox][yellowBox(==redBox)]
// 竖直方向上,先有一个redBox,其下方紧接一个高度等于redBox高度的yellowBox
//
// H:|-10-[Find]-[FindNext]-[FindField(>=20)]-|
// 水平方向上,Find距离父view左边缘默认间隔宽度,之后是FindNext距离Find间隔默认宽度;
// 再之后是宽度不小于20的FindField,它和FindNext以及父view右边缘的间距都是默认宽度。(竖线“|” 表示superview的边缘)
//
//NSLayoutConstraint.constraintsWithVisualFormat(
//format: String,
//options: NSLayoutFormatOptions,
//metrics: [String : AnyObject]?,
//views: [String : AnyObject]
//)
//
// format :VFL语句
// opts :约束类型
// metrics :VFL语句中用到的具体数值
// views :VFL语句中用到的控件

//如果通过代码来设置Autolayout约束, 必须给需要设置约束的视图禁用autoresizing
imgView.translatesAutoresizingMaskIntoConstraints = false
lab.translatesAutoresizingMaskIntoConstraints = false

let viewDict:[String:AnyObject] = ["aa":imgView , "bb":lab]
let metricsDict = ["space":10]
let hVFL = "H:|-space-[aa(50)]-space-[bb(<=150)]"
let hArrLayoutConstraint = NSLayoutConstraint.constraintsWithVisualFormat(hVFL, options: NSLayoutFormatOptions.AlignAllTop, metrics: metricsDict, views: viewDict)
aView.addConstraints(hArrLayoutConstraint)

let VVFL = "V:[aa(50)]-space-|"
let vArrLayoutConstraint = NSLayoutConstraint.constraintsWithVisualFormat(VVFL, options: NSLayoutFormatOptions.AlignAllLeft, metrics: metricsDict, views: viewDict)
aView.addConstraints(vArrLayoutConstraint)

效果

效果

本文标题:NSLayoutConstraint(VFL)简单使用

文章作者:史彦超

发布时间:2016年10月11日 - 22:10

最后更新:2021年07月20日 - 16:07

原始链接:https://doingself.github.io/2016/10/11/2016-10-11-NSLayoutConstraint%EF%BC%88VFL%EF%BC%89%E7%AE%80%E5%8D%95%E4%BD%BF%E7%94%A8/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Donate comment here