自動布局 NSLayoutConstraint

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博客

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,606評論 6 533
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,582評論 3 418
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,540評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,028評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,801評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,223評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,294評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,442評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,976評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,800評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,996評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,543評論 5 360
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,233評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,662評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,926評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,702評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,991評論 2 374

推薦閱讀更多精彩內容