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