史上比较用心的纯代码实现AutoLayout

KriI95 7年前
   <p>入职有两三个月了吧,都是使用 Objective-C 纯代码(虽然有时候偷偷参杂一些 Swift 开源库)来编写公司APP,写布局的时候几乎都是要么在初始化的时候用 initWithFrame,要么就初始化完毕之后用 view.frame。虽然这种方法很直观,一眼就可以看出这个 view 的位置以及大小,但是坏处也是有的,比如说在计算的时候麻烦等等。</p>    <h3>概述</h3>    <p>使用 Objective-C 纯代码编写 AutoLayout,看 AutoLayout 的字面理解就是自动布局,听起来好像蛮屌的样子。说白了就是适配:适应、兼容各种不同的情况,包括不同版本的操作系统的适配(系统适配)和不同屏幕尺寸的适配(屏幕适配)。</p>    <p>在 Storyboard 中,AutoLayout 有以下 3 个常用面板:</p>    <p>1.Align(对齐)</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/d83e91c189029bb61f68491772b2695d.jpg"></p>    <p>2.Pin(相对)</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/97e30d21780bb75bc025b998703415c5.jpg"></p>    <p>3.Resolve Auto Layout Issues(约束处理)</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/ca95397a6341141ca4c725ff6e11697e.jpg"></p>    <p>在 Storyboard 中实现 AutoLayout 我就不在本文讲解,因为讲了就是违背了不忘初心,方得始终的标题了。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/a68c88386babf9b9ac3bbf7257f5ecc7.jpg"></p>    <p>Talk is cheap, show me the code</p>    <p>先说一下用代码实现 AutoLayout 步骤,别眨眼:</p>    <ol>     <li>利用 NSLayoutConstraint 类创建具体的约束对象;</li>     <li>添加约束对象到相应的 view 上,代码有这两种:</li>    </ol>    <pre>  <code class="language-objectivec">- (void)addConstraint:(NSLayoutConstraint *)constraint;      - (void)addConstraints:(NSArray *)constraints;    </code></pre>    <p>或许有人问了,原来才两个步骤就可以了,我刚刚裤子都脱了,你就给我看这个?!</p>    <p>话不多说,马上 show you the code !</p>    <p>先看看我们使用 frame 的方式是如何确定一个 view 的位置的:</p>    <pre>  <code class="language-objectivec">- (void)viewDidLoad {          [super viewDidLoad];          self.title = @"使用 frame 的方式";          UIView *purpleView = [[UIView alloc] initWithFrame:CGRectMake(100, 200, 150, 150)];          purpleView.backgroundColor = [UIColor purpleColor];          [self.view addSubview:purpleView];      }    </code></pre>    <p>代码很简单,运行效果如下:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/09033352682dadff820d0adb69b94b0b.jpg"></p>    <p>再来看看 AutoLayout 的实现:</p>    <pre>  <code class="language-objectivec">- (void)viewDidLoad {          [super viewDidLoad];          self.title = @"使用 AutoLayout 的方式";          UIView *purpleView = [[UIView alloc] init];          purpleView.backgroundColor = [UIColor purpleColor];          // 禁止将 AutoresizingMask 转换为 Constraints          purpleView.translatesAutoresizingMaskIntoConstraints = NO;          [self.view addSubview:purpleView];                 // 添加 width 约束          NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:purpleViewattribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttributemultiplier:0.0 constant:150];          [purpleView addConstraint:widthConstraint];                 // 添加 height 约束          NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:purpleViewattribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttributemultiplier:0.0 constant:150];          [purpleView addConstraint:heightConstraint];                 // 添加 left 约束          NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:purpleViewattribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeftmultiplier:1.0 constant:100];          [self.view addConstraint:leftConstraint];                 // 添加 top 约束          NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:purpleViewattribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTopmultiplier:1.0 constant:200];          [self.view addConstraint:topConstraint];      }   </code></pre>    <p>看完这段代码,我收到了惊吓!我被这一大段代码吓到了,很多童鞋看到那么简单的布局需要写那么多代码,可能就被吓跑了。我只能说一句:先不要走,待我慢慢解释~</p>    <p>创建约束对象(NSLayoutConstraint)的常用方法</p>    <p>一个 NSLayoutConstraint 对象就代表一个约束。</p>    <pre>  <code class="language-objectivec">+ (id)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c;   </code></pre>    <p>总共有 7 个参数 ,那就以 leftConstraint 为例吧介绍这 7 个参数吧</p>    <ul>     <li>☞ view1: 要约束的控件(purpleView)</li>     <li>☞ attr1: 约束的类型(常量),就是要做怎么样的约束,大家可以进去看看都有什么常量(这里是NSLayoutAttributeLeft)</li>     <li>☞ relation: 与参照控件之间的关系(常量),包括等于、大于等于、小于等于(NSLayoutRelationEqual 是指等于)</li>     <li>☞ view2: 参照的控件(self.view)</li>     <li>☞ attr2: 约束的类型(常量),就是要做怎么样的约束,大家可以进去看看都有什么常量(这里是NSLayoutAttributeLeft)(NSLayoutAttributeLeft)</li>     <li>☞ multiplier: 乘数,就是多少倍(1.0)</li>     <li>☞ c: 常量,做好了上述的约束之后会加上这个常量(100)</li>    </ul>    <p>所以 leftConstraint 就是代表:要约束的控件purpleView 的左间距是等于参照控件 self.view 的左间距的 1.0 倍加上 100。</p>    <p>所以我们得出 AutoLayout 的核心计算公式:</p>    <pre>  <code class="language-objectivec">obj1.property1 =(obj2.property2 * multiplier)+ constant value   </code></pre>    <p>1.添加约束(addConstraint)的规则</p>    <p>在创建约束了之后,需要将其添加到作用的控件上才能生效,注意在添加约束的时候目标控件需要遵循以下规则(这里控件就用 view 简单表示吧):</p>    <p>(1)对于两个同层级 view 之间的约束关系,添加到它们的父 view 上</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/8131b1126f3bd0ebb37bc94b73fba847.png"></p>    <p>对于两个同层级 view 之间的约束关系,添加到它们的父 view 上</p>    <p>(2)对于两个不同层级 view 之间的约束关系,添加到他们最近的共同父 view 上</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/aa513077ef2aaa35ac85ca48bbf81af2.png"></p>    <p>对于两个不同层级 view 之间的约束关系,添加到他们最近的共同父 view 上</p>    <p>(3)对于有层次关系的两个 view 之间的约束关系,添加到层次较高的父 view 上</p>    <p>对于有层次关系的两个 view 之间的约束关系,添加到层次较高的父 view 上</p>    <p>(4)对于比如长宽之类的,只作用在该 view 自己身上的话,添加到该 view 自己上,不用图了吧</p>    <p>可以看出,widthConstraint 和 Constraint 属于第(4)种,leftConstraint 和 rightConstraint 属于第(3)种。</p>    <p>1.代码实现 AutoLayout 的注意事项</p>    <p>如果只是创建和添加了约束,是不能正常运行的,要做好以下的工作:</p>    <p>(1)要先禁止 autoresizing 功能,防止 AutoresizingMask 转换成 Constraints,避免造成冲突,需要设置 view 的下面属性为 NO:</p>    <pre>  <code class="language-objectivec">view.translatesAutoresizingMaskIntoConstraints = NO;   </code></pre>    <p>(2)添加约束之前,一定要保证相关控件都已经在各自的父控件上。用上面的例子就是 [self.view addSubview:purpleView]; 一定要放在添加 left 约束之前,否则程序会 crash,因为要确保 purpleView 要已经在 self.view 上了。建议先写 [self.view addSubview:purpleView]; 之后,再专心写约束。</p>    <p>(3)不用再给 view 设置 frame</p>    <p>看到了吧,那么简单的一个界面,用 AutoLayout 实现的话竟然要那么多代码,感觉上并没有那么方便是吧?</p>    <p>其实 AutoLayout 要看应用内容决定,上面只是一个使用的 demo。如果你的内容是信息众多,同时需要展示的类别也很多,尺寸动态不定,比如说微博列表、QQ 动态列表等等,写这些复杂界面使用 AutoLayout 能给予(jǐ yǔ)很大的帮助。</p>    <p>Apple 为了简化 AutoLayout 复杂的代码,开发了一种 VFL 语言(Visual format language),事实上没看见简化多少,而且还有比较大的局限性,这里就不介绍了,想了解的童鞋自己 Google 去。</p>    <p>算了,给个官方链接吧:</p>    <p>https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/VisualFormatLanguage.html</p>    <p>如何优雅的代码编写 AutoLayout</p>    <p>看到了 Apple 自带的 AutoLayout 实现方式,感觉实在是太恶心了,那么如何优雅的代码编写 AutoLayout 呢?</p>    <p>—— 使用第三方框架 Masonry。GitHub: https://github.com/SnapKit/Masonry 看它的介绍,感觉挺牛掰的:</p>    <p>Harness the power of AutoLayout NSLayoutConstraints with a simplified, chainable and expressive syntax. Supports iOS and OSX Auto Layout.</p>    <p>看完 README.md 文件发现的确蛮优雅的。</p>    <p>先一览 Masonry 是如何实现 AutoLayout 的:</p>    <pre>  <code class="language-objectivec">#import "ViewController.h"      #import "Masonry.h" // 第三方或自己写的用引号,系统自带用双引号。             @interface ViewController ()      @end             @implementation ViewController             - (void)viewDidLoad {          [super viewDidLoad];                 UIView *purpleView = [[UIView alloc] init];          purpleView.backgroundColor = [UIColor purpleColor];          [self.view addSubview:purpleView];                 [purpleView mas_makeConstraints:^(MASConstraintMaker *make) {              // 在这个 block 里面,利用 make 对象创建约束              make.size.mas_equalTo(CGSizeMake(100, 100));              make.center.mas_equalTo(self.view);          }];      }    </code></pre>    <p>运行效果:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/eb25c62f3c9501234d4e7ae635accfb2.jpg"></p>    <p>创建一个长和宽均为 100、与父 view 居中的 view</p>    <p>注意:purpleView.translatesAutoresizingMaskIntoConstraints = NO;不需要在这里写了,因为 Masonry 已经写好了。</p>    <p>Masonry 开车,赶紧上车</p>    <p>一步一步跟着来,哈哈嘻嘻</p>    <pre>  <code class="language-objectivec">// 长宽均为 100,粘着父 view 右下角         [purpleView mas_makeConstraints:^(MASConstraintMaker *make) {             make.width.equalTo(@100);             make.height.equalTo(@100);             make.right.equalTo(self.view);             make.bottom.equalTo(self.view);         }];     </code></pre>    <p style="text-align:center"><img src="https://simg.open-open.com/show/99cbb221f6beb3c31dbe29a01ff763a0.jpg"></p>    <p>长宽均为 100,粘着父 view 右下角</p>    <pre>  <code class="language-objectivec">// 长宽均为 100,粘着父 view 右下角,间距为 16         [purpleView mas_makeConstraints:^(MASConstraintMaker *make) {             make.width.equalTo(@100);             make.height.equalTo(@100);             // 这里也可以写 make.right.equalTo(self.view.mas_right).offset(-16);             // 为了增强可读性,可以在 .offset 前加上 .with 或者 .and: make.right.equalTo(self.view).with.offset(-16); 看自己习惯吧             make.right.equalTo(self.view).offset(-16);             // 这里也可以写 make.right.equalTo(self.view.mas_bottom).offset(-16);             make.bottom.equalTo(self.view).offset(-16);         }];     </code></pre>    <p style="text-align:center"><img src="https://simg.open-open.com/show/478a88d89e9bd4786e7249d63a106f47.png"></p>    <p>长宽均为 100,粘着父 view 右下角,间距为 16</p>    <p>看到上面代码的包装好的 @100,其实也可以直接传值 100,不过要把 equalTo 改成 mas_equalTo,这样它就自动帮你包装好了。</p>    <pre>  <code class="language-objectivec">make.width.mas_equalTo(100);      make.height.mas_equalTo(100);    </code></pre>    <p>其实 mas_equalTo 就是一个宏,大家可以进去看看定义。</p>    <ul>     <li>mas_equalTo 这个方法会对参数进行包装</li>     <li>equalTo 这个方法不会对参数进行包装</li>     <li>mas_equalTo 的功能强于 equalTo</li>    </ul>    <p>大家可能会觉得有点儿晕,有时候用 mas_equalTo,有时候用 equalTo,其实大家可以在 pch 文件里定义两个宏,就可以完美解决这个纠结问题。注意要写在 #import "Masonry.h" 前面。</p>    <pre>  <code class="language-objectivec">//define this constant if you want to use Masonry without the 'mas_' prefix,这样子 `mas_width` 等就可以写成 `width`      #define MAS_SHORTHAND             //define this constant if you want to enable auto-boxing for default syntax,这样子 `mas_equalTo` 和 `equalTo` 就没有区别了      #define MAS_SHORTHAND_GLOBALS    </code></pre>    <p>好,现在来一个稍微比刚才的复杂一点点的界面:</p>    <pre>  <code class="language-objectivec">- (void)viewDidLoad {          [super viewDidLoad];                 UIView *purpleView = [[UIView alloc] init];          purpleView.backgroundColor = [UIColor purpleColor];          [self.view addSubview:purpleView];                 UIView *orangeView = [[UIView alloc] init];          orangeView.backgroundColor = [UIColor orangeColor];          [self.view addSubview:orangeView];                 CGFloat margin = 16;          CGFloat height = 32;          [purpleView mas_makeConstraints:^(MASConstraintMaker *make) {              make.left.equalTo(self.view).offset(margin);              make.bottom.equalTo(self.view).offset(-margin);              make.right.equalTo(orangeView.left).offset(-margin);              make.height.equalTo(height);              make.width.equalTo(orangeView);          }];                 [orangeView mas_makeConstraints:^(MASConstraintMaker *make) {              make.bottom.equalTo(self.view).offset(-margin);              make.right.equalTo(self.view).offset(-margin);              make.height.equalTo(height);          }];      }    </code></pre>    <p style="text-align:center"><img src="https://simg.open-open.com/show/c186e0e805f65c47f1bed41606c24a85.png"></p>    <p>两个等高等宽的 view 平分屏幕宽度,带有间隙</p>    <p>其实实现这个界面有很多中写法,大家可以试试,比如说这样写:</p>    <pre>  <code class="language-objectivec">- (void)viewDidLoad {                   ...                 [purpleView mas_makeConstraints:^(MASConstraintMaker *make) {              make.left.equalTo(self.view).offset(margin);              make.bottom.equalTo(self.view).offset(-margin);              make.right.equalTo(orangeView.left).offset(-margin);              make.height.equalTo(height);              make.height.equalTo(orangeView);              make.width.equalTo(orangeView);              make.top.equalTo(orangeView);          }];                 [orangeView mas_makeConstraints:^(MASConstraintMaker *make) {              make.right.equalTo(self.view).offset(-margin);          }];      }    </code></pre>    <p>总结</p>    <p>其实 Masonry 的文档已经很详细了,建议大家去看文档,我写这个主要是为了做这个界面的 Tableview 上下拉阻尼效果而准备的</p>    <p> </p>    <p>来自:http://mobile.51cto.com/iphone-532236.htm</p>    <p> </p>