- NSLayoutConstraint
- VFL
- Masonry

在開發(fā)中我們經(jīng)常會將XIB、StoryBoard配合AutoLayout 來完成界面的適配,但是很多時(shí)候如果我們需要封裝一個(gè)庫卻不想在庫中使用XIB或者StoryBoard,此時(shí)我們就需要通過純代碼的方式來對屏幕進(jìn)行適配了,這也是今天我想講的主要內(nèi)容,即 如何用純代碼的方式來進(jìn)行屏幕適配
NSLayoutConstraint
我們先說一下使用 NSLayoutConstraint的具體步驟:
- 利用
NSLayoutConstraint類創(chuàng)建具體的約束對象,注意一個(gè)NSLayoutConstraint實(shí)例代表一條約束。 - 添加約束對象到相應(yīng)的 view 上,蘋果為我們提供了兩個(gè)方法:
- (void)addConstraint:(NSLayoutConstraint *)constraint NS_AVAILABLE_IOS(6_0);
- (void)addConstraints:(NSArray<__kindof NSLayoutConstraint *> *)constraints NS_AVAILABLE_IOS(6_0);
下面我們來看一個(gè)具體的例子:
用NSLayoutConstraint實(shí)現(xiàn)一個(gè)寬度高度為100,在父控件中垂直水平居中的效果
UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];
//要先禁止 autoresizing 功能
redView.translatesAutoresizingMaskIntoConstraints = NO;
/**
*參數(shù)一:要約束的控件
*參數(shù)二:約束的類型(做怎樣的約束)
*參數(shù)三:與參照控件之間的關(guān)系
*參數(shù)四:參照的控件
*參數(shù)五:約束的類型(做怎樣的約束)
*參數(shù)六:乘數(shù)
*參數(shù)七:常量
*/
// 添加寬度約束:父控件的一半
NSLayoutConstraint *consW = [NSLayoutConstraint constraintWithItem:redView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeWidth
multiplier:0.5
constant:0.0
];
// 添加高度約束:父控件的一半
NSLayoutConstraint *consH = [NSLayoutConstraint constraintWithItem:redView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.view attribute:NSLayoutAttributeHeight
multiplier:0.5
constant:0.0
];
// 水平居中
NSLayoutConstraint *consX = [NSLayoutConstraint constraintWithItem:redView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0.0
];
// 垂直居中
NSLayoutConstraint *consY = [NSLayoutConstraint constraintWithItem:redView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1.0
constant:0.0
];
[self.view addConstraints:@[consW,consH,consX,consY]];
效果圖如下:

注意事項(xiàng)
- 要先禁止 autoresizing 功能
redView.translatesAutoresizingMaskIntoConstraints = NO; - 添加約束之前,一定要保證相關(guān)控件都已經(jīng)添加到對應(yīng)的父控件上了
- 因?yàn)閕OS中原點(diǎn)在左上角所以使用
offset時(shí)注意right和bottom用負(fù)數(shù)
添加約束的規(guī)則
在創(chuàng)建約束之后,需要將其添加到作用的view上,在添加時(shí)要注意目標(biāo)view需要遵循以下規(guī)則:
-
對于兩個(gè)同層級view之間的約束關(guān)系,添加到它們的父view上image
-
對于兩個(gè)不同層級view之間的約束關(guān)系,添加到他們最近的共同父view上image
-
對于有層次關(guān)系的兩個(gè)view之間的約束關(guān)系,添加到層次較高的父view上 image
VFL(Visual Format Language)
通過上面寬高為100,在父控件中垂直水平居中的簡單效果可以看到復(fù)雜程度,蘋果公司為了簡化這種操作,設(shè)計(jì)了一種 可視化格式語言即:VFL
VFL的思想其實(shí)很簡單,它將約束分成了兩塊即水平方向(H:)和垂直方向(V:)
其實(shí)蘋果官方文檔對 這一塊 描述的特別詳細(xì),這里我就直接貼圖了:




我們來看看官方為我們提供的API
/**
* 參數(shù)一:format VFL格式構(gòu)成的字符串,用以表達(dá)想要添加的約束
* 參數(shù)二:options 對齊方式,是一個(gè)枚舉值
* 參數(shù)三:metrics 一般傳入以間距為KEY的字典,如: @{ @"margin":@20},KEY要與format參數(shù)里所填寫的“margin”相同
* 參數(shù)三:views 傳入約束中提到的View,也是要傳入字典,但是KEY一定要和format參數(shù)里所填寫的View名字相同
*
* @return 返回約束的數(shù)組
*/
+ (NSArray *)constraintsWithVisualFormat:(NSString *)format
options:(NSLayoutFormatOptions)options
metrics:(NSDictionary *)metrics
views:(NSDictionary *)views;
注意:
因?yàn)閰?shù)三和參數(shù)四需要傳入字典,字典的KEY要和Format中的名字相同,如果我們自己去寫 第一比較麻煩,第二不小心還容易寫錯(cuò),所以蘋果為我們提供了一個(gè)強(qiáng)大的宏: NSDictionaryOfVariableBindings
/* This macro is a helper for making view dictionaries
for +constraintsWithVisualFormat:options:metrics:views:
NSDictionaryOfVariableBindings(v1, v2, v3) is equivalent to
[NSDictionary dictionaryWithObjectsAndKeys:v1, @"v1", v2, @"v2", v3, @"v3", nil];
*/
#define NSDictionaryOfVariableBindings(...) _NSDictionaryOfVariableBindings(@"" # __VA_ARGS__, __VA_ARGS__, nil)
為了更清晰的展示VFL的用法 下面我用一個(gè)例子來展示一下:
??例子:用VFL實(shí)現(xiàn)下面的效果:View寬高相等,邊距20

UIView *blueView = [[UIView alloc] init];
blueView.backgroundColor = [UIColor blueColor];
// 不要將AutoresizingMask轉(zhuǎn)為Autolayout的約束
blueView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:blueView];
UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
// 不要將AutoresizingMask轉(zhuǎn)為Autolayout的約束
redView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:redView];
// 間距
NSNumber *margin = @20;
// 添加水平方向的約束
NSString *hFormat = @"H:|-margin-[blueView]-margin-[redView(==blueView)]-margin-|";
//把要添加約束的View轉(zhuǎn)成字典
NSDictionary *views = NSDictionaryOfVariableBindings(blueView, redView);
NSDictionary *mertrics = NSDictionaryOfVariableBindings(margin);
//options: 這里設(shè)置底部和頂部對齊
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:hFormat
options:NSLayoutFormatAlignAllTop
| NSLayoutFormatAlignAllBottom
metrics:mertrics
views:views];
[self.view addConstraints:constraints];
// 添加豎直方向的間距
NSNumber *height = @40;
NSString *vFormat = @"V:[blueView(height)]-margin-|";
NSDictionary *mertrics2 = NSDictionaryOfVariableBindings(margin, height);
NSArray *constraints2 = [NSLayoutConstraint constraintsWithVisualFormat:vFormat
options:kNilOptions
metrics:mertrics2
views:views];
[self.view addConstraints:constraints2];
VFL也是有缺陷的,這話是蘋果自己說的 有圖有真相

所以 這也就引出了下面我想講的東西
Masonry
Masonry
其實(shí)關(guān)于Masonry的用法 其github上的主頁已經(jīng)描述的非常清楚直白了,這里我們直接用Masonry來實(shí)現(xiàn)最開始的小例子
UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
make.size.equalTo(self.view).multipliedBy(0.5);
make.center.equalTo(self.view);//make centerX and centerY = self.view
}];
是不是Soeasy.....代碼量簡單了很多?
比如我們想實(shí)現(xiàn)一個(gè)控件 距離其父控件上下左右都為10的效果:
NSInteger padding = 10;
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(superview).with.insets(padding);
}];
是不是爽爆了....
更多更詳細(xì)的信息可以去其官方文檔上查看


