VFL全称是Visual Format Language,翻译过来是“可视化格式语言”
VFL是苹果公司为了简化Autolayout的编码而推出的抽象语言
VFL示例:
H:[redBtn(100)]-30-[blueBtn(100)]
水平方向上redBtn宽100,blueBtn宽100,它们之间间距30
H:[redView(>=100@700)]
redView宽度大于等于100,该约束条件优先级为700(优先级最大值为1000,优先级越高的约束越先被满足)
V:[redBox][blueBox(==redBox)]
竖直方向上,先有一个redBox,其下方紧接一个高度等于redBox高度的blueBox
H:|-10-[redView]-[blueView]-[yellowView(>=20)]-|
水平方向上,redView距离父view左边缘默认间隔宽度,之后是blueView距离redView间隔默认宽度;再之后是宽度不小于20的yellowView,它和blueView以及父view右边缘的间距都是默认宽度。(竖线“|” 表示superview的边缘)
先子啊使用VFL来实现下图所示的效果:
2个view宽度、高度永远相等,高度等于50,距离父控件左边、右边、下边间距和2个view之间的间距相等,等于30
代码实现如下:
// VFL
UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
// 要先禁止autoresizing功能,设置view的下面属性为NO
redView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:redView];
UIView *blueView = [[UIView alloc] init];
blueView.backgroundColor = [UIColor blueColor];
// 要先禁止autoresizing功能,设置view的下面属性为NO
blueView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:blueView];
NSString *h_vfl = @"H:|-space-[redView(==blueView)]-space-[blueView]-30-|";
NSDictionary *dict = @{@"redView":redView,
@"blueView":blueView
};
NSDictionary *metricsDict = @{@"space":@30};
/**
format :VFL语句
opts :约束类型
metrics :VFL语句中用到的具体数值
views :VFL语句中用到的控件
*/
NSArray *constraintsH = [NSLayoutConstraint constraintsWithVisualFormat:h_vfl options:kNilOptions metrics:metricsDict views:dict];
[self.view addConstraints:constraintsH];
NSString *V_redView_vfl = @"V:[redView(50)]-space-|";
NSArray *constraintsVred = [NSLayoutConstraint constraintsWithVisualFormat:V_redView_vfl options:kNilOptions metrics:metricsDict views:dict];
[self.view addConstraints:constraintsVred];
NSString *V_blue_vfl = @"V:[blueView(50)]-space-|";
NSArray *constraintsVblue = [NSLayoutConstraint constraintsWithVisualFormat:V_blue_vfl options:kNilOptions metrics:metricsDict views:dict];
[self.view addConstraints:constraintsVblue];
// 还有一种方法就是设置redViewg和blueView顶部对齐和底部对齐
// 但这个直接用VFL实现不了,还是要用万能公式
// [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:blueView attribute:NSLayoutAttributeTop multiplier:1 constant:0];