在开发过程中难免会遇到自动布局方面的问题,VFL就是自动布局的一种方法。
VFL:Visual Format Language 可视化格式语言
使用VFL简单分为三个步骤:
1.禁用translatesAutoresizingMaskIntoConstraints
translatesAutoresizingMaskIntoConstraints属性和autolayout有关,如果你定义的view想要使用autolayout,就将translatesAutoresizingMaskIntoConstraints设为NO,如果你使用的不是autolayout,就将translatesAutoresizingMaskIntoConstraints设为YES。
//为了方便封装了一个创建view的方法
-(UIView *)createView:(NSString *)view addToView:(UIView *)sView{
UIView *myView = [[NSClassFromString(view) alloc]init];
myView.translatesAutoresizingMaskIntoConstraints = NO;
[sView addSubview:myView];
return myView;
}
UIView *view1 = [self createView:@"UIView" addToView:self.view];
view1.backgroundColor = [UIColor redColor];
UIView *view2 = [self createView:@"UIView" addToView:self.view];
view2.backgroundColor = [UIColor brownColor];
2.绑定视图和字符串
NSDictionary *views = NSDictionaryOfVariableBindings(view1,view2)
3.添加约束
NSLayoutConstraint约束的类
constraintsWithVisualFormat:VFL语句
options:基于哪一个选项(基于哪个方向去计算布局)
metrics:绑定数值与字符串
views:绑定视图 与字符串
中国语言
view1:
横向:距离父视图左侧100 view1宽度最小是100 距离父视图右侧是100
竖向:距离父视图顶部150 view1的高度是40
可视化语言
view1:
H:|-100-[view1(>=100)]-100-|
V:|-150-[view1(40)]
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-100-[view1(>=100)]-100-|" options:NSLayoutFormatAlignAllLeft metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-150-[view1(40)]" options:NSLayoutFormatAlignAllLeft metrics:nil views:views]];
view2:
横向:距离父视图左侧100 view2宽度最小是100 距离父视图右侧是100
竖向:距离view1 50 view2的高度和view1相同
view2:
H:|-100-[view1(>=100)]-100-|
V:[view1]-50-[view2(view1)]
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-100-[view2(>=100)]-100-|" options:NSLayoutFormatAlignAllLeft metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[view1]-50-[view2(view1)]" options:NSLayoutFormatAlignAllLeft metrics:nil views:views]];