自动布局 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阅读 160,026评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,655评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,726评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,204评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,558评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,731评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,944评论 2 314
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,698评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,438评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,633评论 2 247
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,125评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,444评论 3 255
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,137评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,103评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,888评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,772评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,669评论 2 271

推荐阅读更多精彩内容