AutoLayout概念是蘋果自iOS6開(kāi)始引入的概念。
目前為止,實(shí)現(xiàn)自動(dòng)布局技術(shù)選型方面也可以使用xib和storyboard。在開(kāi)發(fā)過(guò)程中通常登錄、注冊(cè)等變動(dòng)可能性較小的視圖,我會(huì)采用xib開(kāi)發(fā),其他頁(yè)面通常會(huì)采用Masonry布局。xib和手碼各有優(yōu)勢(shì),視情況而定。
關(guān)于NSLayoutAttributeLeading和NSLayoutAttributeTrailing,前邊和后邊并不是總是為左邊和右邊的,有些國(guó)家的前邊是右邊后邊是左邊所以這樣設(shè)定是為了國(guó)際化考慮。還有視圖基準(zhǔn)線NSLayoutAttributeBaseline通常是指視圖的底部放文字的地方。
使用NSLayoutConstraint之前,我們需要確定一點(diǎn):為了防止constraint和view本身的autoresizing屬性沖突,我們需要設(shè)置view的屬性:
view.translatesAutoresizingMaskIntoConstraints = NO;
用代碼來(lái)設(shè)置AutoLayout,我們向需要添加autoLayout的視圖使用該方法:
+(instancetype)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c;
上面方法詳解:
該方法實(shí)際上滿足一個(gè)數(shù)學(xué)關(guān)系
view1 =(>=,<=) multiplier * view2 + constant
參數(shù)說(shuō)明:
view1:是需要添加約束的視圖.
attr1: 是view1選擇的屬性,什么樣的位置 (上,下,左,右,中心點(diǎn)等)添加約束.
relation: 中間的關(guān)系 (=, >=, <=)
multiplier: 乘因子,就是倍數(shù)
view2: 添加約束的參照視圖
attr2: 是view2選擇的屬性,相對(duì)什么樣的位置(上,下,左,右,中心點(diǎn)等).
constant: 就是偏移量?
理解什么原理最好的方法就是舉例,那就舉個(gè)例子:
例子: 設(shè)置第一個(gè)視圖是第二個(gè)視圖寬度的2倍, 第一個(gè)視圖為view1,第二個(gè)視圖為view2
?[self.view addSubview:self.view1];
? ? [self.view addSubview:self.view2];
? ? NSLayoutConstraint * view1_top = [NSLayoutConstraint constraintWithItem:self.view1 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:100];
? ? NSLayoutConstraint * view1_left = [NSLayoutConstraint constraintWithItem:self.view1 attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:20];
? ? NSLayoutConstraint * view1_width = [NSLayoutConstraint constraintWithItem:self.view1 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:0 constant:200];
? ? NSLayoutConstraint * view1_height = [NSLayoutConstraint constraintWithItem:self.view1 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:0 constant:200];
//把約束添加到父視圖上
? ? [self.viewaddConstraints:@[view1_top, view1_left, view1_width, view1_height]];
? ? NSLayoutConstraint * view2_top = [NSLayoutConstraint constraintWithItem:self.view2 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view1 attribute:NSLayoutAttributeBottom multiplier:1 constant:10];
? ? NSLayoutConstraint * view2_left = [NSLayoutConstraint constraintWithItem:self.view2 attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view1 attribute:NSLayoutAttributeLeft multiplier:1 constant:0];
? ? NSLayoutConstraint * view2_width = [NSLayoutConstraint constraintWithItem:self.view2 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view1 attribute:NSLayoutAttributeWidth multiplier:2 constant:0];
? ? NSLayoutConstraint * view2_height = [NSLayoutConstraint constraintWithItem:self.view2 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view1 attribute:NSLayoutAttributeHeight multiplier:1 constant:0];
//把約束添加到父視圖上
? ? [self.viewaddConstraints:@[view2_top, view2_left, view2_width, view2_height]];
我們所有可以控制的屬性:
這里解釋一下前邊NSLayoutAttributeLeading和后邊NSLayoutAttributeTrailing,這里前邊和后邊并不是總是為左邊和右邊的,有些國(guó)家的前邊是右邊后邊是左邊所以這樣設(shè)定是為了國(guó)際化考慮。還有視圖基準(zhǔn)線NSLayoutAttributeBaseline通常是指視圖的底部放文字的地方。
這里講一下比較容易犯錯(cuò)的地方:
1、添加約束前確定已經(jīng)把需要布局的子view添加到父view上了
2、一定要禁止將Autoresizing Mask轉(zhuǎn)換為約束
3、要把子view的約束加在父view上
4、因?yàn)閕OS中原點(diǎn)在左上角所以使用offset時(shí)注意right和bottom用負(fù)數(shù)
子view在父view的中間,且子view長(zhǎng)300,高200。
[self.view setBackgroundColor:[UIColor redColor]];
? ? //創(chuàng)建子view
? ? UIView*subView = [[UIViewalloc]init];
? ? [subViewsetBackgroundColor:[UIColor blackColor]];
? ? [self.viewaddSubview:subView];
? ? //使用Auto Layout約束,禁止將Autoresizing Mask轉(zhuǎn)換為約束
? ? [subViewsetTranslatesAutoresizingMaskIntoConstraints:NO];
? ? //layout 子view
? ? //子view的中心橫坐標(biāo)等于父view的中心橫坐標(biāo)
? ? NSLayoutConstraint *constrant1 = [NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0];
? ? //子view的中心縱坐標(biāo)等于父view的中心縱坐標(biāo)
? ? NSLayoutConstraint *constrant2 = [NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0];
? ? //子view的寬度為300
? ? NSLayoutConstraint *constrant3 = [NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:300.0];
? ? //子view的高度為200
? ? NSLayoutConstraint *constrant4 = [NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:200.0];
? ? //把約束添加到父視圖上
? ? NSArray*array = [NSArray arrayWithObjects:constrant1, constrant2, constrant3, constrant4,nilnil];
? ? [self.view addConstraints:array];
這里需要注意的是:
1、如果是設(shè)置view自身的屬性,不涉及到與其他view的位置約束關(guān)系。比如view自身的寬、高等約束時(shí),方法constraintWithItem:的第四個(gè)參數(shù)view2(secondItem)應(yīng)設(shè)為
nil;且第五個(gè)參數(shù)attr2(secondAttribute)應(yīng)設(shè)為?NSLayoutAttributeNotAnAttribute?。
2、在設(shè)置寬和高這兩個(gè)約束時(shí),relatedBy參數(shù)使用的是?NSLayoutRelationGreaterThanOrEqual,而不是?NSLayoutRelationEqual。因?yàn)?Auto Layout 是相對(duì)布局,所以通常你不應(yīng)該直接設(shè)置寬度和高度這種固定不變的值,除非你很確定視圖的寬度或高度需要保持不變。
更新/修改約束
先來(lái)看一下 NSLayoutConstraint 的API,貌似只有constant屬性可以修改,其它都是只讀的。所以對(duì)于現(xiàn)有約束的修改和更新都是圍繞NSLayoutConstraint實(shí)例的constant屬性展開(kāi)的。
1、如果你是使用 Xib/StoryBoard 的話,在程序運(yùn)行時(shí)想動(dòng)態(tài)的改變視圖的約束,你可以這樣做:
約束Constraint也可以像控件一樣做IBOutlet鏈接,通過(guò)拖線關(guān)聯(lián)到文件。(事例這里是改變子view相對(duì)于父view的top約束)
首先在你的ViewController的頭文件里定義一個(gè)約束屬性:
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *topConstraint ;
#import @interface LayoutConstraintViewController : UIViewController
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *topConstraint;
@end
然后在XIB里選中 File’s Owner,選中Outlet欄目。將對(duì)應(yīng)的Outlet拖動(dòng)到View對(duì)應(yīng)Constraint連接起來(lái)就可以了。跟button/label做鏈接一摸一樣的。
這樣我們就可以獲得view上面的某個(gè)具體約束了,然后就可以在文件中對(duì)這個(gè)約束進(jìn)行我們想要的修改。
//更新約束
self.topConstraint.constant = 10;
總結(jié)來(lái)說(shuō)就是:拖線關(guān)聯(lián)到文件獲得約束,修改約束的constant屬性。
2、如果你是使用 Xib/StoryBoard ,但是不想通過(guò)上述拉線的方式獲得約束然后再去更新它,你還可以采用代碼的方式修改約束:
但是無(wú)論采用哪種方式,我們都要遵循Auto Layout 的約束更新機(jī)制:想要更新視圖上面的約束,就要先找到對(duì)應(yīng)的約束再去更新它。遍歷view上面的所有約束,查找到要更新的約束再進(jìn)行更新。
所以我們要像上面一樣要先獲得top約束。在代碼中的體現(xiàn)就是通過(guò)約束的標(biāo)識(shí)字段,在其父view的constraints數(shù)組中遍歷查找。這是因?yàn)槊總€(gè)view的constraints數(shù)組中保存的實(shí)際上是 layout 子view所需的約束的集合。
我們可以通過(guò)下面的輔助函數(shù)實(shí)現(xiàn):
NSArray *constrains = self.view.constraints;
for (NSLayoutConstraint* constraint in constrains)?
{
????if (constraint.firstAttribute == NSLayoutAttributeTop) {
????constraint.constant = 10;
????}
}
這里只判斷了一個(gè)標(biāo)識(shí)字段(NSLayoutAttributeTop),但是大多數(shù)情況下view上面的約束依賴不會(huì)那么簡(jiǎn)單,所以需要查找判斷多個(gè)標(biāo)識(shí)字段,才能找到。
3、如果你是使用代碼布局,那就用上面2介紹的方法更新約束,或者在添加約束之前先將該約束記錄下來(lái),方便后面的更新修改。
Auto Layout 關(guān)于更新約束的幾個(gè)方法
setNeedsLayout:告知頁(yè)面需要更新,但是不會(huì)立刻開(kāi)始更新。執(zhí)行后會(huì)立刻調(diào)用layoutSubviews。
layoutIfNeeded:告知頁(yè)面布局立刻更新。所以一般都會(huì)和setNeedsLayout一起使用。如果希望立刻生成新的frame需要調(diào)用此方法,利用這點(diǎn)一般布局動(dòng)畫可以在更新布局后直接使用這個(gè)方法讓動(dòng)畫生效。
layoutSubviews:系統(tǒng)重寫布局。
setNeedsUpdateConstraints:告知需要更新約束,但是不會(huì)立刻開(kāi)始。
updateConstraintsIfNeeded:告知立刻更新約束。
updateConstraints:系統(tǒng)更新約束。
這么多方法中,目前我使用比較多的是 layoutIfNeeded 。因?yàn)樵贏uto Layout 實(shí)現(xiàn)動(dòng)畫的時(shí)候,layoutIfNeeded 方法可以立刻生成新的frame特性是一大利器。
使用 Auto Layout (NSLayoutConstraint)實(shí)現(xiàn)動(dòng)畫
目前貌似還有很多人對(duì)于 Auto Layout 的動(dòng)畫實(shí)現(xiàn)還不是很了解。畢竟以前我們處理動(dòng)畫之類的交互大都是和view的frame屬性打交道,即使用傳統(tǒng)的 animation方法修改view的frame。大致類似于
CGRectnewFrame = view.frame;
? ? newFrame.size.height =300;
? ? [UIView animateWithDuration:3.0 animations:^{
? ? ? ? view.frame = newFrame;
? ? }completion:^(BOOLfinished) {
? ? }];
那么在Auto Layout下我們又該如何處理相關(guān)的動(dòng)畫呢?根據(jù)前面說(shuō)到的Auto Layout布局約束的原理,在某個(gè)時(shí)刻約束也是會(huì)被還原成frame使視圖顯示,這個(gè)時(shí)刻可以通過(guò)layoutIfNeeded這個(gè)方法來(lái)進(jìn)行控制,可以立刻生成新的frame并展示出來(lái),從而實(shí)現(xiàn)動(dòng)畫效果。
//start animations
? ? //先根據(jù)初始化添加的約束生成最初的frame并顯示view
? ? [self.view layoutIfNeeded];
? ? [UIView animateWithDuration:3.0 animations:^{
? ? ? ? //遍歷查找view的heigh約束,并修改它
? ? ? ? NSArray*constrains =self.view.constraints;
? ? ? ? for(NSLayoutConstraint* constraintinconstrains) {
? ? ? ? ? ? if (constraint.firstAttribute == NSLayoutAttributeHeight) {
? ? ? ? ? ? ? ? constraint.constant=300;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? //更新約束? 在某個(gè)時(shí)刻約束會(huì)被還原成frame使視圖顯示
? ? ? ? [self.view layoutIfNeeded];
? ? }completion:^(BOOLfinished) {
? ? }];
參考:?IOS--通過(guò)代碼方式使用AutoLayout (NSLayoutConstraint + Masonry) - timtian008的博客 - CSDN博客