前言:
说到自动布局,Autoresizing已经满足不了我们加约束的需求,而Autolayout功能强大,应用比较普遍,但有时候需要用代码来加约束,这时候用Autolayout就比较麻烦了,代码繁琐不说,代码量也是大大滴有!想对Autoresizing和Autolayout代码加约束的使用有个了解,可以去我另一篇博客中去了解一下(http://blog.csdn.net/zlj_jeck/article/details/51460433).而现在有一种VFL语法可以代替Autolayout进行约束,相比之下,VFL语法更加简单明了且生动直观的就把约束给加上了.想要源码的朋友,可以去我的GitHub下载源码(https://github.com/zlj-jeck/VFLDemo),里边注释也很清楚,相信能帮助大家更好的理解VFL语法.
进入正题:
首先上两张图帮助我们理解,第一张图是运行效果图,第二张图是辅助讲解图,不要晕哦,开始上图:
然后上代码
- (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor grayColor]; //VFL语法总结: //(1)“H”表示水平方向,“V”表示垂直方向 //(2)“|”表示父视图的边界 //(3)“[]”表示这是一个视图UIView的子类,可以组合多个条件,条件用"()",多个条件用逗号隔开,例如:[view(>=100,<200)] //(4)“@”表示优先级 // (5) VFL语法适配分为横向和垂直方向,对两个方向分别考虑,两个方向上互不影响,各自管各自的 //创建子视图(这里以button为例,只做个演示,没给方法,也可以是view) UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom]; leftButton.backgroundColor = [UIColor redColor]; [self.view addSubview:leftButton]; UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom]; rightButton.backgroundColor = [UIColor greenColor]; [self.view addSubview:rightButton]; UIButton *bottomButton = [UIButton buttonWithType:UIButtonTypeCustom]; bottomButton.backgroundColor = [UIColor purpleColor]; [self.view addSubview:bottomButton]; //关闭Autoresizing(使用VFL语法加约束,必须先将子视图的Autoresizing关闭,否则会出问题),切记:这几行不能忘记 [leftButton setTranslatesAutoresizingMaskIntoConstraints:NO]; [rightButton setTranslatesAutoresizingMaskIntoConstraints:NO]; [bottomButton setTranslatesAutoresizingMaskIntoConstraints:NO]; NSMutableArray *mutArray = [[NSMutableArray alloc] init];
//设置横向约束
//横1 [mutArray addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[leftButton]-20-[rightButton(==leftButton)]-20-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(leftButton,rightButton)]]; //横2 [mutArray addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[bottomButton]-20-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(bottomButton)]];
//设置垂直的约束
//竖1 [mutArray addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[leftButton]-20-[bottomButton(==leftButton)]-20-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(leftButton,bottomButton)]]; //竖2 [mutArray addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[rightButton(==leftButton)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(rightButton,leftButton)]]; [self.view addConstraints:mutArray];
//VFL学习网址://https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/AutoLayoutbyExample/AutoLayoutbyExample.html#//apple_ref/doc/uid/TP40010853-CH5-SW1