深入理解IOS控件布局之Masonry布局框架

2020-01-18 20:49:41于丽

前言:

回想起2013年做iOS开发的时候,那时候并没有采用手写布局代码的方式,而是采用xib文件来编写,如果使用纯代码方式是基于window的size(320,480)计算出一个相对位置进行布局,那个时候windows的size是固定不变的,随着iphone5的发布,windows的size(320,568)也发生了变化,而采用autoresizingMask的方式进行适配,到后来iphone 6之后windows size的宽度也随之变化,开始抛弃autoresizingMask改用autolayout了,使用autolayout进行适配我也是最近重新做iOS开发才接触的,公司使用Masonry框架进行布局适配。所以学习使用这个布局框架对我来说至关重要,它大大提高了开发效率而且最近使用起来很多语法和Android有很大的相似之处。

什么是Masonry?

Masonry是一个轻量级的布局框架,拥有自己的描述语法,采用更优雅的链式语法封装ios/118384.html">自动布局、简洁明了、 并具有高可读性、 而且同时支持 iOS 和 Max OS X。

如何使用?

1.)引入头文件

我这里是在全局引用pch文件中引用的


#import "Masonry.h"

2.)基本语法

Masonry提供的属性

@property (nonatomic, strong, readonly) MASConstraint *left;//左侧 @property (nonatomic, strong, readonly) MASConstraint *top;//上侧 @property (nonatomic, strong, readonly) MASConstraint *right;//右侧 @property (nonatomic, strong, readonly) MASConstraint *bottom;//下侧 @property (nonatomic, strong, readonly) MASConstraint *leading;//首部 @property (nonatomic, strong, readonly) MASConstraint *trailing;//尾部 @property (nonatomic, strong, readonly) MASConstraint *width;//宽 @property (nonatomic, strong, readonly) MASConstraint *height;//高 @property (nonatomic, strong, readonly) MASConstraint *centerX;//横向居中 @property (nonatomic, strong, readonly) MASConstraint *centerY;//纵向居中 @property (nonatomic, strong, readonly) MASConstraint *baseline;//文本基线

Masonry提供了三个函数方法

- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block; //新增约束 - (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block;//更新约束 - (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block;//清楚之前的所有约束,只会保留最新的约束

我们根据不同的使用场景来选择使用不同的函数方法。

3.)具体举例

  比如一个往父控件中添加一个上下左右与父控件间距为50的子视图

添加约束


  UIView *tempView=[[UIView alloc]init];
  tempView.backgroundColor=[UIColor greenColor];
  [self.view addSubview:tempView];
  
  [tempView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.mas_equalTo(50);
    make.right.mas_equalTo(-50);
    make.top.mas_equalTo(50);
    make.bottom.mas_equalTo(-50);
  }];