iOS開發-自動布局篇:史上最牛的自動布局教學!


轉載自:http://www.jianshu.com/p/f6cf9ef451d9

本文我們將提到:

  1. aotulayout(手碼)
  2. VFL
  3. aotulayout(Xib)
  4. Masonry(第三方框架)

是不是很期待呢?那就跟着小編走吧!
本文Demo地址:https://github.com/JinqianChina/aotulayoutDemo.git

一、AutoLayout介紹

UI布局對於iOS開發者來說並不陌生,在iOS6之前,大家都是通過UI控件的Frame屬性和Autoresizing Mask來進行UI布局的。AutoLayout則是蘋果公司在iOS6推出的一種基於約束的,描述性的布局系統。自從AutoLayout問世以來,逐步得到了iOS開發者們的青睞,尤其是iPhone6機型尺寸的出現,讓AutoLayout從此走向人生巔峰,迎娶白富美,當上UI布局界的老大。~_~,好了,不扯淡了,下面來看看它的特殊之處。

AutoLayout占據UI布局的主要領導位置依賴於它的特殊性:

1).基於約束:和以往定義frame的位置和尺寸不同,AutoLayout的位置確定是以所謂相對位置的約束來定義的,比如x坐標為superView的中心,y坐標為屏幕底部上方10像素等
2).描述性: 約束的定義和各個view的關系使用接近自然語言或者可視化語言(稍后會提到)的方法來進行描述
3).布局系統:即字面意思,用來負責界面的各個元素的位置。

總而言之,AutoLayout為開發者提供了一種不同於傳統對於UI元素位置指定的布局方法。以前,不論是在IB里拖放,還是在代碼中寫,每個UIView都會有自己的frame屬性,來定義其在當前視圖中的位置和尺寸。使用AutoLayout的話,就變為了使用約束條件來定義view的位置和尺寸。這樣的最大好處是一舉解決了不同分辨率和屏幕尺寸下view的適配問題,另外也簡化了旋轉時view的位置的定義,原來在底部之上10像素居中的view,不論在旋轉屏幕或是更換設備(iPad或者iPhone5或者以后可能出現的mini iPad)的時候,始終還在底部之上10像素居中的位置,不會發生變化。 總的來說:使用約束條件來描述布局,view的frame會依據這些約束來進行計算。

二、AutoLayout使用原理:

  1. 創建約束,iOS6中新加入了一個類:NSLayoutConstraint。它的約束滿足這個公式:

     item1.attribute = multiplier ⨉ item2.attribute + constant

    對應的代碼為

     //view_1(紅色)top 距離self.view的top NSLayoutConstraint *view_1TopToSuperViewTop = [NSLayoutConstraint constraintWithItem:view_1 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:30];

    這里對應的約束是“view_1的頂部(y)= self.view的頂部(y)*1 + 30”。

  2. 添加約束,在創建約束之后,需要將其添加到作用的view上。UIView添加約束的實例方法:

     - (void)addConstraint:(NSLayoutConstraint *)constraint NS_AVAILABLE_IOS(6_0); - (void)addConstraints:(NSArray<__kindof NSLayoutConstraint *> *)constraints NS_AVAILABLE_IOS(6_0);

    用來將約束添加到view。在添加時唯一要注意的是添加的目標view要遵循以下規則:

    1).對於兩個同層級view之間的約束關系,添加到他們的父view上


    Mou icon

    2).對於兩個不同層級view之間的約束關系,添加到他們最近的共同父view上


    Mou icon

    3).對於有層次關系的兩個view之間的約束關系,添加到層次較高的父view上


    Mou icon
  3. 刷新約束,可以通過-setNeedsUpdateConstraints和-layoutIfNeeded兩個方法來刷新約束的改變,使UIView重新布局。

三、AutoLayout的不同使用方式

OK,到這里我們講了一堆理論,相信對AutoLayout對不熟悉的童鞋依然比較迷茫,你必須要進行代碼的洗禮,才會對它大徹大悟。好的,那么我們開始上代碼吧!

如圖1:我們需要布局紅、綠、藍三個view位置如圖所示,他們距離父視圖邊距以及相互之間的距離都為30px,紅色view和綠色view寬度相等,並且三個view的高度相等。並且在橫屏時,他們的位置還是一樣保持不變。


Mou icon

Mou icon

Mou icon

如果用傳統布局方式利用Frame屬性,則需要分情況來判斷並改變控件Frame的值以達到適應屏幕的尺寸。下面來看看AutoLayout自動布局的實現方法:

  1. AutoLayout(系統手碼)

     - (void)viewDidLoad { [super viewDidLoad]; /* * 需求 * * 我們需要布局紅(view_1)、綠(view_2)、藍(view_3)三個view位置如圖所示, * 他們距離父視圖邊距以及相互之間的距離都為30px,紅色view和綠色view寬度相等, * 並且三個view的高度相等。並且在橫屏時,他們的位置還是一樣保持不變。 * */ //1.首先,創建視圖控件,添加到self.view上 UIView *view_1 = [[UIView alloc] init]; view_1.backgroundColor = [UIColor redColor]; [self.view addSubview:view_1]; UIView *view_2 = [[UIView alloc] init]; view_2.backgroundColor = [UIColor greenColor]; [self.view addSubview:view_2]; UIView *view_3 = [[UIView alloc] init]; view_3.backgroundColor = [UIColor blueColor]; [self.view addSubview:view_3]; //2.然后,記得要把AutoresizingMask布局關掉 view_1.translatesAutoresizingMaskIntoConstraints = NO; view_2.translatesAutoresizingMaskIntoConstraints = NO; view_3.translatesAutoresizingMaskIntoConstraints = NO; //3.接着,添加約束,先添加邊距約束,再添加寬高約束(個人習慣) /* * 添加約束 公式:item1.attribute = multiplier ⨉ item2.attribute + constant */ //view_1(紅色)top 距離self.view的top NSLayoutConstraint *view_1TopToSuperViewTop = [NSLayoutConstraint constraintWithItem:view_1 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:30]; //view_1(紅色)left 距離self.view的left NSLayoutConstraint *view_1LeftToSuperViewLeft = [NSLayoutConstraint constraintWithItem:view_1 attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:30]; //view_1(紅色)right 距離view_2(綠色)的left NSLayoutConstraint *view_1RightToview_2Left = [NSLayoutConstraint constraintWithItem:view_2 attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:view_1 attribute:NSLayoutAttributeRight multiplier:1 constant:30]; //view_1(紅色)bottom 距離view_3(藍色)的top NSLayoutConstraint *view_1BottomToview_3Top = [NSLayoutConstraint constraintWithItem:view_1 attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:view_3 attribute:NSLayoutAttributeTop multiplier:1 constant:- 30]; //view_2(綠色)right 距離self.view的right NSLayoutConstraint *view_2RightToSuperViewRight = [NSLayoutConstraint constraintWithItem:view_2 attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1 constant:- 30]; //view_2(綠色)centerY 和 view_1(紅色)的centerY 一致 NSLayoutConstraint *view_2CenterYToView_1CenterY = [NSLayoutConstraint constraintWithItem:view_2 attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:view_1 attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]; //view_3(藍色)left 距離 self.view left NSLayoutConstraint *view_3LeftToSuperViewLeft = [NSLayoutConstraint constraintWithItem:view_3 attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:30]; //view_3(藍色)right 距離 self.view right NSLayoutConstraint *view_3RightToSuperViewRight = [NSLayoutConstraint constraintWithItem:view_3 attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1 constant:- 30]; //view_3(藍色)Bottom 距離 self.view bottom NSLayoutConstraint *view_3BottomToSuperViewBottom = [NSLayoutConstraint constraintWithItem:view_3 attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1 constant:- 30]; //view_1(紅色)width 和view_2(綠色)的width相等 NSLayoutConstraint *view_1WidthToview_2Width = [NSLayoutConstraint constraintWithItem:view_2 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:view_1 attribute:NSLayoutAttributeWidth multiplier:1 constant:0]; //view_1(紅色)height 和view_2(綠色)的height相等 NSLayoutConstraint *view_1HeightToview_2Height = [NSLayoutConstraint constraintWithItem:view_2 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:view_1 attribute:NSLayoutAttributeHeight multiplier:1 constant:0]; //view_1(紅色)height 和 view_3(藍色)的height相等 NSLayoutConstraint *view_1HeightToview_3Height = [NSLayoutConstraint constraintWithItem:view_3 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:view_1 attribute:NSLayoutAttributeHeight multiplier:1 constant:0]; //添加約束,因為view_1、2、3是同層次關系,且他們公有的父視圖都是self.view,所以這里把約束都添加到self.view上即可 [self.view addConstraints:@[view_1TopToSuperViewTop,view_1LeftToSuperViewLeft,view_1RightToview_2Left,view_2RightToSuperViewRight,view_1WidthToview_2Width,view_1BottomToview_3Top,view_2CenterYToView_1CenterY,view_3LeftToSuperViewLeft,view_3RightToSuperViewRight,view_3BottomToSuperViewBottom,view_1HeightToview_2Height,view_1HeightToview_3Height]]; [self.view layoutIfNeeded]; }

    看到這里,相信大家要哭了吧,為毛就寫這三個視圖要這么麻煩,沒錯,小編這里就是用來惡心你的,哈哈!其實,我去研究它的時候,也是被惡心的要死,沒辦法,為了幫助大家對AutoLayout進行深入理解,小編也是拼了(ps:其實我在項目中基本不用這個系統手碼的)。還好,蘋果還給我們提供了一種可視化自然語言用於自動布局的約束:VFL(Visual Format Language),簡化了添加約束。

  2. VFL約束

     - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. /* * 需求 * * 我們需要布局紅(view_1)、綠(view_2)、藍(view_3)三個view位置如圖所示, * 他們距離父視圖邊距以及相互之間的距離都為30px,紅色view和綠色view寬度相等, * 並且三個view的高度相等。並且在橫屏時,他們的位置還是一樣保持不變。 * */ //1.首先,創建視圖控件,添加到self.view上 UIView *view_1 = [[UIView alloc] init]; view_1.backgroundColor = [UIColor redColor]; [self.view addSubview:view_1]; UIView *view_2 = [[UIView alloc] init]; view_2.backgroundColor = [UIColor greenColor]; [self.view addSubview:view_2]; UIView *view_3 = [[UIView alloc] init]; view_3.backgroundColor = [UIColor blueColor]; [self.view addSubview:view_3]; //2.然后,記得要把AutoresizingMask布局關掉 view_1.translatesAutoresizingMaskIntoConstraints = NO; view_2.translatesAutoresizingMaskIntoConstraints = NO; view_3.translatesAutoresizingMaskIntoConstraints = NO; //3.接着,添加約束 // 間距 NSNumber *margin = @(30); NSNumber *spacing = @(30); NSDictionary *views = NSDictionaryOfVariableBindings(view_1,view_2,view_3); // 添加水平方向的約束1 NSString *vfl = @"H:|-margin-[view_1]-spacing-[view_2(==view_1)]-margin-|"; NSDictionary *mertrics = NSDictionaryOfVariableBindings(margin,spacing); NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:vfl options:NSLayoutFormatAlignAllTop | NSLayoutFormatAlignAllBottom metrics:mertrics views:views]; [self.view addConstraints:constraints]; // 添加水平方向的約束2 NSString *vfl1 = @"H:|-margin-[view_3]-margin-|"; NSDictionary *mertrics1 = NSDictionaryOfVariableBindings(margin,spacing); NSArray *constraints1 = [NSLayoutConstraint constraintsWithVisualFormat:vfl1 options:kNilOptions metrics:mertrics1 views:views]; [self.view addConstraints:constraints1]; // 添加豎直方向的約束 NSString *vfl2 = @"V:|-margin-[view_1]-spacing-[view_3(==view_1)]-margin-|"; NSDictionary *mertrics2 = NSDictionaryOfVariableBindings(margin, spacing); NSArray *constraints2 = [NSLayoutConstraint constraintsWithVisualFormat:vfl2 options:kNilOptions metrics:mertrics2 views:views]; [self.view addConstraints:constraints2]; }

    看了VFL語言約束,是不是瞬間感覺高大上了許多,按照我們所想,依次寫出約束VFL語句即可。這樣雖然比系統手碼方便多了,但是仍然需要寫很多代碼,小編下面要告訴你的是,不用寫一行約束代碼就能完成上面約束需求,那就是Xib可視化添加約束,下面來看看吧!

  3. Xib可視化添加約束

    (1)首先,先拖拽三個UIview視圖,如圖。注意:這里我們只是暫時大致擺了一下位置,還沒有添加約束。


    Mou icon

    (2)view_1紅色視圖添加約束,如圖,添加上和左距離父視圖都是30px


    Mou icon

    (3)view_2綠色視圖添加約束,如圖,添加左和右分別距離view_1和父視圖的距離都是30px


    Mou icon

    (4)view_2添加約束,如圖,直接點擊view_2拖拽到view_1上,然后選擇Center Vertically、Equal Widths和Equal Heights,則添加了view_2約束:豎直方向上中心和view_1一致、寬度和高度也和view_1相等


    Mou icon

    Mou icon

    (5)view_3藍色視圖添加約束,如圖,添加左、下、右距離父視圖的值都為30,上距離view_1的距離為30,並且高度和view_1相等


    Mou icon

    (7)如圖,約束已經添加完成,點擊左側的黃色警告補全視圖差值


    Mou icon

    (8)如圖,則是我們布局完成后的Xib,運行效果就是開頭那個GIF圖效果,是不是很炫酷!


    Mou icon

    Mou icon

    到這里,是不是感覺很神奇了呢,不用一行代碼,就可以完成上述那么多代碼實現的效果。至此,Aotulayout布局已經基本介紹完了,對了,還有一個第三方庫Masonry。

  4. Masonry第三方庫

    Masonry是一個輕量級的布局框架,擁有自己的描述語法,采用更優雅的鏈式語法封裝自動布局,簡潔明了 並具有高可讀性,而且同時支持iOS和Max OS X。

    下面簡單說明一下Masonry:

    先來看一段官方的sample code來認識一下Masonry

     [view1 mas_makeConstraints:^(MASConstraintMaker *make) { make.edges.equalTo(superview).with.insets(padding); }];

    我們看到block里面的那句話: make edges equalTo superview with insets。這里通過鏈式的自然語言,就把view1給autolayout設置好了,看着是不是挺簡單的?更符合我們編程的思想。

    再來看一看它的屬性:

     @property (nonatomic, strong, readonly) MASViewAttribute *left; @property (nonatomic, strong, readonly) MASViewAttribute *top; @property (nonatomic, strong, readonly) MASViewAttribute *right; @property (nonatomic, strong, readonly) MASViewAttribute *bottom; @property (nonatomic, strong, readonly) MASViewAttribute *leading; @property (nonatomic, strong, readonly) MASViewAttribute *trailing; @property (nonatomic, strong, readonly) MASViewAttribute *width; @property (nonatomic, strong, readonly) MASViewAttribute *height; @property (nonatomic, strong, readonly) MASViewAttribute *centerX; @property (nonatomic, strong, readonly) MASViewAttribute *centerY; @property (nonatomic, strong, readonly) MASViewAttribute *baseline; @property (nonatomic, strong, readonly) MASViewAttribute *(^attribute)(NSLayoutAttribute attr); #if TARGET_OS_IPHONE @property (nonatomic, strong, readonly) MASViewAttribute *leftMargin; @property (nonatomic, strong, readonly) MASViewAttribute *rightMargin; @property (nonatomic, strong, readonly) MASViewAttribute *topMargin; @property (nonatomic, strong, readonly) MASViewAttribute *bottomMargin; @property (nonatomic, strong, readonly) MASViewAttribute *leadingMargin; @property (nonatomic, strong, readonly) MASViewAttribute *trailingMargin; @property (nonatomic, strong, readonly) MASViewAttribute *centerXWithinMargins; @property (nonatomic, strong, readonly) MASViewAttribute *centerYWithinMargins;

    是不是覺得很眼熟?沒錯,它和我們系統的NSLayoutConstraint類下的NSLayoutAttribute枚舉一致,這樣就不難理解了,Masonry其實就是把我們系統的NSLayoutConstraint類等Aotulayout布局相關進行了封裝,曝露出比較簡單易懂(鏈式的自然語言)的Aotulayout接口,方便廣大iOS開發者使用。

     typedef NS_ENUM(NSInteger, NSLayoutAttribute) { NSLayoutAttributeLeft = 1, NSLayoutAttributeRight, NSLayoutAttributeTop, NSLayoutAttributeBottom, NSLayoutAttributeLeading, NSLayoutAttributeTrailing, NSLayoutAttributeWidth, NSLayoutAttributeHeight, NSLayoutAttributeCenterX, NSLayoutAttributeCenterY, NSLayoutAttributeBaseline, NSLayoutAttributeLastBaseline = NSLayoutAttributeBaseline, NSLayoutAttributeFirstBaseline NS_ENUM_AVAILABLE_IOS(8_0), NSLayoutAttributeLeftMargin NS_ENUM_AVAILABLE_IOS(8_0), NSLayoutAttributeRightMargin NS_ENUM_AVAILABLE_IOS(8_0), NSLayoutAttributeTopMargin NS_ENUM_AVAILABLE_IOS(8_0), NSLayoutAttributeBottomMargin NS_ENUM_AVAILABLE_IOS(8_0), NSLayoutAttributeLeadingMargin NS_ENUM_AVAILABLE_IOS(8_0), NSLayoutAttributeTrailingMargin NS_ENUM_AVAILABLE_IOS(8_0), NSLayoutAttributeCenterXWithinMargins NS_ENUM_AVAILABLE_IOS(8_0), NSLayoutAttributeCenterYWithinMargins NS_ENUM_AVAILABLE_IOS(8_0), NSLayoutAttributeNotAnAttribute = 0 };

    好了,簡單說明之后,讓我們更實際的來些代碼吧!同樣是上面的需求哦!come on
    首先,要導入Masonry庫文件,這里要打一下廣告了,Masonry 源碼地址:https://github.com/Masonry/Masonry 你可以直接下載,然后將文件拖入工程,也可以使用cocoapods導入,如果不明白cocoapods怎么用的,可以看一下小編的一篇關於cocoapods的介紹:http://www.jianshu.com/p/c23eeb43438b

    OK,看看Masonry神奇的代碼吧!

     - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. /* * 需求 * * 我們需要布局紅(view_1)、綠(view_2)、藍(view_3)三個view位置如圖所示, * 他們距離父視圖邊距以及相互之間的距離都為30px,紅色view和綠色view寬度相等, * 並且三個view的高度相等。並且在橫屏時,他們的位置還是一樣保持不變。 * */ //1.首先,創建視圖控件,添加到self.view上 UIView *view_1 = [[UIView alloc] init]; view_1.backgroundColor = [UIColor redColor]; [self.view addSubview:view_1]; UIView *view_2 = [[UIView alloc] init]; view_2.backgroundColor = [UIColor greenColor]; [self.view addSubview:view_2]; UIView *view_3 = [[UIView alloc] init]; view_3.backgroundColor = [UIColor blueColor]; [self.view addSubview:view_3]; //2.然后,記得要把AutoresizingMask布局關掉 view_1.translatesAutoresizingMaskIntoConstraints = NO; view_2.translatesAutoresizingMaskIntoConstraints = NO; view_3.translatesAutoresizingMaskIntoConstraints = NO; //3.接着,添加約束 __weak __typeof(self) weakSelf = self;//這里用一個弱引用來表示self,用於下面的Block中 //先確定view_1的約束 [view_1 mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(weakSelf.view.mas_top).with.offset(30); //view_1的上,距離self.view是30px make.left.equalTo(weakSelf.view.mas_left).with.offset(30); //view_1de左,距離self.view是30px }]; //然后確定view_2的約束 [view_2 mas_makeConstraints:^(MASConstraintMaker *make) { make.centerY.equalTo(view_1.mas_centerY).with.offset(0); //view2 Y方向上的中心線和view_1相等 make.left.equalTo(view_1.mas_right).with.offset(30); //view2 的左距離view_1的右距離為30px make.right.equalTo(weakSelf.view.mas_right).with.offset(-30); //view_2的右距離self.view30px make.width.equalTo(view_1); //view_2的寬度和view_1相等 make.height.equalTo(view_1); //view_2的高度和view_1相等 }]; //最后確定view_3的約束 [view_3 mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(view_1.mas_bottom).with.offset(30); //view_3的上距離view_1的底部 30px make.left.equalTo(weakSelf.view.mas_left).with.offset(30); //view_3的左距離self.view 30px make.bottom.equalTo(weakSelf.view.mas_bottom).with.offset(30);//view_3的底部距離self.view 30px make.right.equalTo(weakSelf.view.mas_right).with.offset(-30); //view_3的右距離self.view 30px make.height.equalTo(view_1);//view_3的高度和view_1相等 }]; }

    運行效果就是上面的GIF圖,Masonry雖然也寫了不少代碼,但是他看起來比較簡單易懂,在實戰項目中,我們可以用Masonry作為Xib的輔助工具使用,利用代碼處理一些動態的約束。

    最后說明一下,在Masonry中能夠添加autolayout約束有三個函數:

     - (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block; - (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block; - (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block; /* mas_makeConstraints 只負責新增約束 Autolayout不能同時存在兩條針對於同一對象的約束 否則會報錯 mas_updateConstraints 針對上面的情況 會更新在block中出現的約束 不會導致出現兩個相同約束的情況 mas_remakeConstraints 則會清除之前的所有約束 僅保留最新的約束 三種函數善加利用 就可以應對各種情況了 */

喜歡的童鞋,動一下小手點擊喜歡和關注喔!小編在這里附上以上四種自動布局Demo:https://github.com/JinqianChina/aotulayoutDemo.git

參考文章:
http://www.cocoachina.com/ios/20141219/10702.html Masonry介紹與使用實踐:快速上手Autolayout



文/Jingege(簡書作者)
原文鏈接:http://www.jianshu.com/p/f6cf9ef451d9
著作權歸作者所有,轉載請聯系作者獲得授權,並標注“簡書作者”。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM