iOS学习笔记36-Masonry自动布局

一、Masonry介绍

之前我们在屏幕适配的章节中学习过AutoLayout的使用,但那都是在可视化界面上进行添加约束完成的,我们很多时候都需要在代码中使用AutoLayout约束,苹果也为我们提供了实现,使用NSLayoutConstraint类表示约束,但使用起来比较复杂,代码量比较大,例如创建一个约束的方法:

+ (id)constraintWithItem:(id)view1 /* 一个UIView */
               attribute:(NSLayoutAttribute)attribute1 /* 属性 */
               relatedBy:(NSLayoutRelation)relation /* 关系 */
                  toItem:(id)view2 /* 另一个UIView */
               attribute:(NSLayoutAttribute)attribute2 /* 属性 */
              multiplier:(CGFloat)multiplier /* 倍数 */
                constant:(CGFloat)constant; /* 偏移 */

如果约束一多,这个方法调用次数就会越多,代码就会变得很长。

实际上我们可以使用第三方框架Masonry,该框架是一个轻量级的布局框架,封装了AutoLayout,拥有自己的描述语法,采用更优雅的链式语法,简洁明了,并具有高可读性。

Masonry基本支持AutoLayout的所有属性:
 @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;
这些属性与NSLayoutAttrubute的对照表如下:

二、Masonry使用

Masonry的大部分方法都为UIView实现了分类,使我们可以十分简单的使用

下面是Masonry添加约束的方法:
/* 添加新约束,只负责新增约束,不能同时存在两条针对于同一对象的约束,否则会报错 */
- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block;
/* 更新原有的约束,针对上面的情况,会更新在block中出现的约束,不会导致出现两个相同约束的情况 */
- (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block;
/* 删除之前约???,重新添加约束,会清除之前的所有约束,仅保留最新的约束 */
- (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block;
  • 上面三个方法不仅只有UIView可以调用,存有UIViewNSArray数组也可以调用,表示遍历数组中所有UIView进行调用
下面是Block中使用的常见约束语法,[attribute]表示属性,[value]表示值:
/*
   属性attribute可以连用,比如top.right.bottom.left
   加mas_前缀和没有mas_前缀效果差不多,只是加mas_前缀会对参数装箱,
   参数有结构体的时候,需要使用mas_前缀,没有mas_前缀的参数必须为对象
*/
/* 数值约束,top对应NSInteger,center对应NSPoint,size对应NSSize */
make.[attribute].mas_equalTo([value]);
/* 等于约束,两个view之间比较,注意:没有other.edges的属性,edges对应otherView */
make.[attribute].equalTo(otherView.[attribute]);
/* 大于等于约束,两个view之间比较 */
make.[attribute].greaterThanOrEqualTo(otherView.[attribute]);
/* 小于等于约束,两个view之间比较 */
make.[attribute].lessThanOrEqualTo(otherView.[attribute]);
/* 偏移约束 */
make.[attribute].equalTo(otherView.[attribute]).offset([value]);
/* 边界约束,有上、下、左、右边界 */
make.edges.equalTo(otherView).insets(UIEdgeInsetsMake([topValue],[leftValue],[bottomValue],[rightValue]));
/* Margin约束 */
make.[attribute].equalTo(otherView.[attribute]Margin);
注意:

添加约束前,必须先把UIView添加到父视图中,否则会闪退

下面我们通过几个实例来理解:
1. 实例一[基础]:居中显示一个view
- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *sv = [[UIView alloc] init];
    sv.backgroundColor = [UIColor blackColor];
    //一定要先将view添加到superView上,否则会出错
    [self.view addSubview:sv];
    //Masonry的autolayout添加约束
    __weak ViewController *weakSelf = self;
    [sv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(weakSelf.view);//将sv居中
        make.size.mas_equalTo(CGSizeMake(300, 300));//将sv的尺寸设置为(300,300)
    }];
}

2. 实例二[初级]:让一个view略小于其superView(边距为10)
UIView *sv = [[UIView alloc] init];
sv.backgroundColor = [UIColor blackColor];
//一定要先将view添加到superView上,否则会出错
[self.view addSubview:sv];
//Masonry的autolayout添加约束
__weak ViewController *weakSelf = self;
[sv mas_makeConstraints:^(MASConstraintMaker *make) {
    make.center.equalTo(weakSelf.view);//将sv居中
    make.size.mas_equalTo(CGSizeMake(300, 300));//将sv的尺寸设置为(300,300)
}];
UIView *sv1 = [[UIView alloc] init];
sv1.backgroundColor = [UIColor redColor];
//一定要先将view添加到superView上,否则会出错
[sv addSubview:sv1];
//Masonry的autolayout添加约束
[sv1 mas_makeConstraints:^(MASConstraintMaker *make) {
    make.edges.equalTo(sv).with.insets(UIEdgeInsetsMake(10, 10, 10, 10));
    /* 等价于
    make.top.equalTo(sv).with.offset(10);
    make.left.equalTo(sv).with.offset(10);
    make.bottom.equalTo(sv).with.offset(-10);
    make.right.equalTo(sv).with.offset(-10);
    */
    /* 也等价于
    make.top.left.bottom.and.right.equalTo(sv).with.insets(UIEdgeInsetsMake(10, 10, 10, 10));
    */
}];

实际上and和with这两个方法什么事情都没做:
- (MASConstraint *)with {
    return self;
}
- (MASConstraint *)and {
    return self;
}
3. 实例三[初级]:让两个高度为150的view垂直居中且等宽且等间隔排列,间隔为10(自动计算其宽度)
UIView *sv = [[UIView alloc] init];
sv.backgroundColor = [UIColor blackColor];
//一定要先将view添加到superView上,否则会出错
[self.view addSubview:sv];
//Masonry的autolayout添加约束
__weak ViewController *weakSelf = self;
[sv mas_makeConstraints:^(MASConstraintMaker *make) {
    make.center.equalTo(weakSelf.view);//将sv居中
    make.size.mas_equalTo(CGSizeMake(300, 300));//将sv的尺寸设置为(300,300)
}];
int padding1 = 10;
UIView *leftView = [[UIView alloc] init];
leftView.backgroundColor = [UIColor orangeColor];
[sv addSubview:leftView];
UIView *rightView = [[UIView alloc] init];
rightView.backgroundColor = [UIColor orangeColor];
[sv addSubview:rightView];
//Masonry的autolayout添加约束
[leftView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerY.mas_equalTo(sv.mas_centerY);//中心Y轴和sv中心Y轴相等
    make.left.equalTo(sv.mas_left).with.offset(padding1);//左边距离sv的左边界10
    make.right.equalTo(rightView.mas_left).with.offset(-padding1);//右边距离rightView的左边界-10
    make.height.mas_equalTo(@150);//高度150
    make.width.equalTo(rightView);//宽度等于rightView
}];
[rightView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerY.mas_equalTo(sv.mas_centerY);//中心Y轴和sv中心Y轴相等
    make.left.equalTo(leftView.mas_right).with.offset(padding1);//左边距离leftView的右边界10
    make.right.equalTo(sv.mas_right).with.offset(-padding1);//右边距离sv的右边界-10
    make.height.mas_equalTo(@150);//高度150
    make.width.equalTo(leftView);//宽度等于leftView
}];

4. 实例四[中级]:在UIScrollView顺序排列一些view并自动计算contentSize
UIView *sv = [[UIView alloc] init];
sv.backgroundColor = [UIColor blackColor];
//一定要先将view添加到superView上,否则会出错
[self.view addSubview:sv];
//Masonry的autolayout添加约束
__weak ViewController *weakSelf = self;
[sv mas_makeConstraints:^(MASConstraintMaker *make) {
    make.center.equalTo(weakSelf.view);//将sv居中
    make.size.mas_equalTo(CGSizeMake(300, 300));//将sv的尺寸设置为(300,300)
}];
/* 创建ScrollView */
UIScrollView *scrollView = [[UIScrollView alloc] init];
scrollView.backgroundColor = [UIColor whiteColor];
[sv addSubView:scrollView];
[scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
    //设置边界约束
    make.edges.equalTo(sv).with.insets(UIEdgeInsetsMake(5,5,5,5));
}];
//创建ScrollView子视图容器视图
UIView *container = [[UIView alloc] init];
[scrollView addSubView:container];
//添加container约束
[container mas_makeConstraints:^(MASConstraintMaker *make) {
    make.edges.equalTo(scrollView);//边界紧贴ScrollView边界
    make.width.equalTo(scrollView);//宽度和ScrollView相等
}];
//向container添加多个View
int count = 10;
UIView *lastView = nil;
for(int i = 1;i <= count;++i ){
    //创建一个View
    UIView *subView = [[UIView alloc] init];
    [container addSubView:subView];
    //颜色随机
    subView.backgroundColor = [UIColor colorWithRed:( arc4random() % 256 / 256.0 )
                                              green:( arc4random() % 256 / 256.0 )
                                               blue:( arc4random() % 256 / 256.0 )
                                              alpha:1];
    //向subView添加约束
    [subView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(container);//左右边界和container紧贴
        make.height.mas_equalTo(@(20*i));//高度随i递增
        //判断是否有前一个子View
        if ( lastView ) {
            //如果有前一个View,上边界和前一个View的下边界紧贴
            make.top.mas_equalTo(lastView.mas_bottom);
        } else {
            //如果没有前一个View,上边界和container的下边界紧贴
            make.top.mas_equalTo(container.mas_top);
        }
    }];
    //保存前一个View
    lastView = subView;
}
//添加container的最后一个约束
[container mas_makeConstraints:^(MASConstraintMaker *make) {
    //container的下边界和最后一个View的下边界紧贴
    make.bottom.equalTo(lastView.mas_bottom);
}];

三、Masonry进阶

Masonry为NSArray实现了2个特殊的分类方法:
/*
    该方法只有存有UIView的NSArray数组可以调用,NSArray里面的UIView必须有共同的spuerView
    该方法作用是UIView之间的水平等宽定距约束,或者垂直等高定距约束。
    先确定间距,宽度或高度不确定,但相等
    axisType只有MASAxisTypeHorizontal(水平间距类型)和MASAxisTypeVertical(垂直间距类型)
    fixedSpacing是UIView两两之间的间距大小
    leadSpacing是第一个UIView距离superView左(或上)边界的间距大小
    tailSpacing是最后一个UIView距离superView右(或下)边界的间距大小
    数组里的所有UIView水平宽度相等,或者垂直高度相等
*/
- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType
                    withFixedSpacing:(CGFloat)fixedSpacing
                         leadSpacing:(CGFloat)leadSpacing
                         tailSpacing:(CGFloat)tailSpacing;

/*
    该方法只有存有UIView的NSArray数组可以调用,NSArray里面的UIView必须有共同的spuerView
    该方法作用是UIView之间的水平定宽等距约束,或者垂直定高等距约束。
    先确定宽度或高度,间距不确定,但相等
    axisType只有MASAxisTypeHorizontal(水平间距类型)和MASAxisTypeVertical(垂直间距类型)
    fixedSpacing是UIView两两之间的间距大小
    leadSpacing是第一个UIView距离superView左(或上)边界的间距大小
    tailSpacing是最后一个UIView距离superView右(或下)边界的间距大小
    数组里的所有UIView间距相等
*/
- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType
                 withFixedItemLength:(CGFloat)fixedItemLength
                         leadSpacing:(CGFloat)leadSpacing
                         tailSpacing:(CGFloat)tailSpacing;
下面是等间距方法的使用实例:
/*
    设置水平等宽定距
    UIView之间水平间距为20,第一个UIView距离superView左边6,
    最后一个UIView距离superView右边7,UIView高度为60,距离顶部40
*/
[array mas_distributeViewsAlongAxis:MASAxisTypeHorizontal
                   withFixedSpacing:20
                        leadSpacing:6
                        tailSpacing:7];
[array mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(@40);
    make.height.equalTo(@60);
}];
/*
    设置水平定宽等距
    所有UIView的宽度为20,第一个UIView距离superView左边6,
    最后一个UIView距离superView右边7,UIView高度为60,距离顶部40
*/
[array mas_distributeViewsAlongAxis:MASAxisTypeHorizontal
                withFixedItemLength:20
                        leadSpacing:6
                        tailSpacing:7];
[array mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(@40);
    make.height.equalTo(@60);
}];
有什么问题可以在下方评论区中提出!O(∩_∩)O哈!

时间: 2024-08-24 03:31:33

iOS学习笔记36-Masonry自动布局的相关文章

iOS: 学习笔记, 用代码驱动自动布局实例

iOS自动布局是设置iOS界面的利器. 本实例展示了如何使用自动布局语言设置水平布局, 垂直布局 1. 创建空白iOS项目 2. 添加一个控制器类, 修改YYAppDelegate.m文件 #import "YYAppDelegate.h" #import "YYViewController.h" @implementation YYAppDelegate - (BOOL)application:(UIApplication *)application didFin

iOS: 学习笔记, 用代码驱动自动布局实例(swift)

iOS自动布局是设置iOS界面的利器.本实例展示了如何使用自动布局语言设置水平布局, 垂直布局1. 创建空白iOS项目(swift)2. 添加一个控制器类, 修改YYAppDelegate.swift文件 @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFi

iOS: 学习笔记, 添加一个带界面约束的控制器

1. 创建一个空iOS应用程序(Empty Application). 2. 添加加控制器类. 修改控制器类的viewDidLoad 1 - (void)viewDidLoad 2 { 3 [super viewDidLoad]; 4 //创建标题 5 UILabel *header = [[UILabel alloc] init]; 6 header.text = @"欢迎来到我的世界!"; 7 header.textAlignment = NSTextAlignmentCenter

IOS学习笔记-- SQLite的应用

1 // 2 // HMViewController.m 3 // 02-SQLite的应用 4 // 5 // Created by apple on 14-7-24. 6 // Copyright (c) 2014年 heima. All rights reserved. 7 // 8 9 #import "HMViewController.h" 10 #import <sqlite3.h> 11 12 @interface HMViewController () 13

iOS学习笔记---c语言第九天

高级指针 指向结构体变量的指针,称为结构体指针 可以使用->指向内容. %p打印地址 void pLenth(cPoint *p1,cPoint *p2) //求两点间的距离  用的开方函数sqrt()和平方函数pow(,) { float a = sqrt(pow((p1->x-p2->x), 2)+pow((p1->y-p2->y), 2)); printf("两点距离为%.2f\n",a); } //main.m中代码 #import <Fou

iOS: 学习笔记, 使用performSelectorOnMainThread及时刷新UIImageView

在iOS中, 界面刷新在主线程中进行, 这导致NSURLSession远程下载图片使用UIImageView直接设置Image并不能及时刷新界面. 下面的代码演示了如何使用 performSelectorOnMainThread: withObject:  waitUntilDone: 方法来及时刷新图片 1. 创建iOS空应用程序(Empty Application). 2. 加入一个控制器类. 在YYAppDelegate.m中修改 #import "MainViewController.h

黑马程序员--IOS学习笔记--数组及排序

IOS学习笔记 概述: 8_2.改变整型变量的符号 8_2.改变整型变量所占存储空间 8_3.char类型数据存储 8_4.数组的基本概念及分类 8_5.数组元素作为函数参数 8_5.一维数组定义及注意事项 8_6.一维数组初始化 8_7.一维数组一个让人疑惑的问题 8_8.一维数组的引用 8_9.应用:数组遍历 8_10.一维数组的存储方式 8_11.一维数组的地址 8_12.一维数组长度计算方法 8_13.一维数组的越界问题 8_14.应用:找最大值 8_15.数组元素作为函数参数 8_16

iOS学习笔记---c语言第十一天

函数指针 一.函数指针定义 //函数声明:声明我是一个什么函数 //求两个数的和 //函数的类型:int (int x,int y) //即:我是一个返回值为整型,有两个整型参数的函数. //函数名是 sum int sum(int x,int y); 函数指针定义p是变量,其他是类型(通常没有形参a,b) //函数指针类型 int (*)(int x,int y) //描述:指向 返回值为 int 两个int参数 的 指针类型 //函数指针变量: p //初始值 : sum printf("%

iOS学习笔记之UITableViewController&amp;UITableView

iOS学习笔记之UITableViewController&UITableView 写在前面 上个月末到现在一直都在忙实验室的事情,与导师讨论之后,发现目前在实验室完成的工作还不足以写成毕业论文,因此需要继续思考新的算法.这是一件挺痛苦的事情,特别是在很难找到与自己研究方向相关的文献的时候.也许网格序列水印这个课题本身的研究意义就是有待考证的.尽管如此,还是要努力的思考下去.由于实验室的原因,iOS的学习进度明显受到影响,加之整理文档本身是一件耗费时间和精力的事情,因此才这么久没有写笔记了. M

iOS: 学习笔记, Swift操作符定义

Swift操作符可以自行定义, 只需要加上简单的标志符即可. @infix 中置运算. 如+,-,*,/运算 @prefix 前置运算. 如- @postfix 后置运算. a++, a-- @assignment 赋值运算. +=, -=, --a, ++a // // main.swift // SwiftBasic // // Created by yao_yu on 14-7-27. // Copyright (c) 2014年 yao_yu. All rights reserved.