如何搞定Autolayout,远离自动布局带给你的烦恼

首先让我们了解一下什么是Autolayout

  • Autolayout是一种“自动布局”技术,专门用来布局UI界面的
  • Autolayout自iOS 6开始引入,由于Xcode 4的不给力,当时并没有得到很大推广
  • 自iOS 7(Xcode 5)开始,Autolayout的开发效率得到很大的提升
  • 苹果官方也推荐开发者尽量使用Autolayout来布局UI界面
  • Autolayout能很轻松地解决屏幕适配的问题

(一)下面让我们用例子来进一步了解Autolayout

示例如下:


效果图.png

代码实现Autolayout的步骤

  • 利用NSLayoutConstraint类创建具体的约束对象
  • 添加约束对象到相应的view上
  - (void)addConstraint:(NSLayoutConstraint *)constraint;
  - (void)addConstraints:(NSArray *)constraints;

代码实现Autolayout的注意点

  • 要先禁止autoresizing功能,设置view的下面属性为NO
view.translatesAutoresizingMaskIntoConstraints = NO;
  • 添加约束之前,一定要保证相关控件都已经在各自的父控件上
  • 不用再给view设置frame

创建约束对象的常用方法

创建约束对象的常用方法
+(id)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c;
view1 :要约束的控件
attr1 :约束的类型(做怎样的约束)
relation :与参照控件之间的关系
view2 :参照的控件
attr2 :约束的类型(做怎样的约束)
multiplier :乘数
c :常量

要用苹果的方法代码实现如下:(额,敲得我【恶心他妈给恶心开门----恶习到家了,不过不要担心请接着往下看】)


#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIView *blueView = [[UIView alloc] init];
    blueView.backgroundColor = [UIColor blueColor];
    // 禁止Autoresizing转为Autolayout的约束
    blueView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:blueView];
    
    
    UIView *redView = [[UIView alloc] init];
    redView.backgroundColor = [UIColor redColor];
    // 禁止Autoresizing转为Autolayout的约束
    redView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:redView];
 
    // 添加蓝色控件的约束
    NSLayoutConstraint *blueLeftLc = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:20];
       [self.view addConstraint:blueLeftLc];
    NSLayoutConstraint *blueBottomLc = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-20];
    [self.view addConstraint:blueBottomLc];
    
    NSLayoutConstraint *buleRightLc = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:redView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:-20];
    [self.view addConstraint:buleRightLc];
    
    NSLayoutConstraint *blueHLc = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:40];
    [self.view addConstraint:blueHLc];
    
    NSLayoutConstraint *blueWidthLc = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:redView attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0];
    [self.view addConstraint:blueWidthLc];

    /*** 添加红色控件的约束 ***/
    NSLayoutConstraint *redTopLc = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:blueView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
    [self.view addConstraint:redTopLc];
    
    NSLayoutConstraint *redBottomLc = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:blueView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
    [self.view addConstraint:redBottomLc];
    
    NSLayoutConstraint *redRightLc = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:-20];
    [self.view addConstraint:redRightLc];
}


@end

OK看到就这么一个简单的效果要这么多代码,是不是想要抓狂,不要心慌,下面我们介绍目前最流行的Autolayout第三方框架---Masonry

同样的让我们先大致了解一个Masonry的一些情况

  • 目前最流行的Autolayout第三方框架

  • 用优雅的代码方式编写Autolayout

  • 省去了苹果官方恶心的Autolayout代码

  • 大大提高了开发效率

  • 框架地址:
    https://github.com/SnapKit/Masonry

上面的效果图用Masonry实现如下:

#import "ViewController.h"

//define this constant if you want to use Masonry without the 'mas_' prefix
#define MAS_SHORTHAND

//define this constant if you want to enable auto-boxing for default syntax
#define MAS_SHORTHAND_GLOBALS

#import "Masonry.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    // 创建蓝色View
    UIView *blueView = [[UIView alloc] init];
    blueView.backgroundColor = [UIColor blueColor];
    [self.view addSubview:blueView];
    
    // 创建红色View
    UIView *redView = [[UIView alloc] init];
    redView.backgroundColor = [UIColor redColor];
    [self.view addSubview:redView];
    
    // 给蓝色View添加约束
    [blueView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.left).offset(20);
        make.bottom.equalTo(self.view.bottom).offset(-20);
        make.right.equalTo(redView.left).offset(-20);
        make.height.equalTo(40);
        make.width.equalTo(redView.width);
        
    }];
    
    // 给红色View添加约束
    [redView makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.right).offset(-20);
        make.top.equalTo(blueView.top);
        make.bottom.equalTo(blueView.bottom);
   
    }];
    
    // 更新约束
    [blueView updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(80);
    }];
}

@end


上面这段代码是不是让你的心情大爽了呢,激动之余细心的读者可能发现,咦#import "Masonry.h"上面怎么有两个宏呢,下面我们来了解一下这是为什么呢

首先是Masonry中的mas_equalToequalTo

  • 默认情况下

    • mas_equalTo有自动包装功能,比如自动将20包装为@20
    • equalTo没有自动包装功能
  • 如果添加了下面的宏,那么mas_equalTo和equalTo就没有区别

#define MAS_SHORTHAND_GLOBALS
// 注意:这个宏一定要添加到#import "Masonry.h"前面

其次是Masonry中的mas_widthwidth

  • 默认情况下

    • width是make对象的一个属性,用来添加宽度约束用的,表示对宽度进行约束
    • mas_width是一个属性值,用来当做equalTo的参数,表示某个控件的宽度属性
  • 如果添加了下面的宏,mas_width也可以写成width

 #define MAS_SHORTHAND

 mas_height、mas_centerX以此类推

总之这样简单高效的方法让我们程序员用的好爽不是吗

(二)开发中我们会遇到这样的问题- 使用到约束的优先级

  • 为了大家更方便的学习我就不用代码实现了,在Storyboard中添加约束
  • 先看一下效果图
// 点击屏幕时会调用此方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //
    [self.blueView removeFromSuperview];
    // 利用2s的时间去更新约束,在修改了约束之后,只要执行下面代码,就能做动画效果,感兴趣的读者可以试一下
    [UIView animateWithDuration:2 animations:^{
      
        // 强制更新约束(让self.view以及它的所有子控件都强制更新)
        [self.view layoutIfNeeded];
    }];
   
}
约束优先级.gif

OK这样的效果怎么实现呢,给大家看两张图大家就明白约束优先级的用处了

  • 绿色与蓝色的约束优先级值


    绿色与蓝色的约束优先级值.png
  • 绿色与红色的约束优先级值
绿色与红色的约束优先级值.png
  • 从上面可以看出绿色与蓝色的约束优先级值大于绿色与红色的约束优先级值,所以当3个View都存在时执行绿色与蓝色的约束优先级值,
    当点击屏幕,移除绿色View时绿色与蓝色的约束优先级值无效了,执行绿色与红色的约束优先级值,故此可以实现以上效果

谢谢各位耐心观看,如有问题请留言我会及时更新改正,谢谢大家,祝各位每天开心!!!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容