背景
一直以来我们App
布局都是很不统一的,原因是每个开发者所处的环境不同,而导致的,有的开发者一直只会用一种,但如果遇到一个新的项目中没有他熟悉的布局就会很头痛。这篇文章主要介绍一个Apple
开发中一直存在的部局方式 VFL
VFL介绍
VFL全称是Visual Format Language,翻译过来是“可视化格式语言”
VFL是苹果公司为了简化Autolayout的编码而推出的抽象语言
VFL语法
H:|[redView(50)]-20-[blueView(50)]|
redView宽50,blueView宽50,它们之间间距20
H:|[redView(>=60@700)]|
redView宽度大于等于60point,该约束条件优先级为700(优先级最大值为1000,优先级越高的约束条件越先被满足)
V:|[redView][blueView(==redView)]|
垂直方向上,先有一个redView,其下方紧接一个高度等于redView高度的blueView
H:|-10-[userLabel]-[userNameLabel]-[userNameText(>=20)]-|
水平方向上,userLabel距离父view左边缘间隔10,之后是userNameLabel距离userLabel间隔默认宽度;再之后是宽度不小于20的userNameText,它和userNameLabel以及父view右边边缘的间距都是默认宽度。(竖线“|”表示superview的边缘)。
VFL使用
UIView *redView = [[UIView alloc] init];
redView.backgroundColor = UIColor.redColor;
redView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:redView];
UIView *blueView = [[UIView alloc] init];
blueView.translatesAutoresizingMaskIntoConstraints = NO;
blueView.backgroundColor = UIColor.blueColor;
[self.view addSubview:blueView];
//把所view加到Dictionary中去
NSDictionary *dictionary = NSDictionaryOfVariableBindings(redView,blueView);
//水平方向的约束
NSString *hVFL = @"H:|-30-[blueView]-30-[redView(==blueView)]-30-|";
NSArray *hCons = [NSLayoutConstraint constraintsWithVisualFormat:hVFL options:NSLayoutFormatAlignAllBottom | NSLayoutFormatAlignAllTop metrics:nil views:dictionary];
[self.view addConstraints:hCons];
//垂直方向的约束
NSString *vVFL = @"V:|-100-[blueView(50)]-[redView(==blueView)]-|";
NSArray *vCons = [NSLayoutConstraint constraintsWithVisualFormat:vVFL options:0 metrics:nil views:dictionary];
[self.view addConstraints:vCons];
VFL
布局主要采用NSLayoutConstraint constraintsWithVisualFormat:options:metrics: views:
方法实现的。
constraintsWithVisualFormat
是布局的格式
options
选项,可以通过那个方向去布局
metrics
对应的参数字典,比如:@{@"width":@20}
,就可以写成V:|-wdith-[blueView(50)]-[redView(==blueView)]-|
views
参于布局的View
字典
总结
功能 | 表达式 |
---|---|
水平方向 | H: |
垂直方向 | V: |
Views | [view] |
SuperView | | |
关系 | >=,==,<= |
空间,间隙 | - |
优先级 | @value |