背景
一直以來(lái)我們App
布局都是很不統(tǒng)一的厂捞,原因是每個(gè)開(kāi)發(fā)者所處的環(huán)境不同,而導(dǎo)致的,有的開(kāi)發(fā)者一直只會(huì)用一種靡馁,但如果遇到一個(gè)新的項(xiàng)目中沒(méi)有他熟悉的布局就會(huì)很頭痛欲鹏。這篇文章主要介紹一個(gè)Apple
開(kāi)發(fā)中一直存在的部局方式 VFL
VFL介紹
VFL全稱是Visual Format Language,翻譯過(guò)來(lái)是“可視化格式語(yǔ)言”
VFL是蘋果公司為了簡(jiǎn)化Autolayout的編碼而推出的抽象語(yǔ)言
VFL語(yǔ)法
H:|[redView(50)]-20-[blueView(50)]|
redView寬50臭墨,blueView寬50貌虾,它們之間間距20
H:|[redView(>=60@700)]|
redView寬度大于等于60point,該約束條件優(yōu)先級(jí)為700(優(yōu)先級(jí)最大值為1000裙犹,優(yōu)先級(jí)越高的約束條件越先被滿足)
V:|[redView][blueView(==redView)]|
垂直方向上尽狠,先有一個(gè)redView,其下方緊接一個(gè)高度等于redView高度的blueView
H:|-10-[userLabel]-[userNameLabel]-[userNameText(>=20)]-|
水平方向上叶圃,userLabel距離父view左邊緣間隔10袄膏,之后是userNameLabel距離userLabel間隔默認(rèn)寬度;再之后是寬度不小于20的userNameText掺冠,它和userNameLabel以及父view右邊邊緣的間距都是默認(rèn)寬度沉馆。(豎線“|”表示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:
方法實(shí)現(xiàn)的德崭。
constraintsWithVisualFormat
是布局的格式
options
選項(xiàng)斥黑,可以通過(guò)那個(gè)方向去布局
metrics
對(duì)應(yīng)的參數(shù)字典,比如:@{@"width":@20}
眉厨,就可以寫成V:|-wdith-[blueView(50)]-[redView(==blueView)]-|
views
參于布局的View
字典
總結(jié)
功能 | 表達(dá)式 |
---|---|
水平方向 | H: |
垂直方向 | V: |
Views | [view] |
SuperView | | |
關(guān)系 | >=,==,<= |
空間锌奴,間隙 | - |
優(yōu)先級(jí) | @value |