iOS VFL使用与布局

背景

一直以来我们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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容