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

2024-04-01 20:48

本文主要是介绍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 (nonatomicstrongreadonly) MASConstraint *left;@property (nonatomicstrongreadonly) MASConstraint *top;@property (nonatomicstrongreadonly) MASConstraint *right;@property (nonatomicstrongreadonly) MASConstraint *bottom;@property (nonatomicstrongreadonly) MASConstraint *leading;@property (nonatomicstrongreadonly) MASConstraint *trailing;@property (nonatomicstrongreadonly) MASConstraint *width;@property (nonatomicstrongreadonly) MASConstraint *height;@property (nonatomicstrongreadonly) MASConstraint *centerX;@property (nonatomicstrongreadonly) MASConstraint *centerY;@property (nonatomicstrongreadonly) 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(300300));//将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(300300));//将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(300300));//将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的左边界10make.right.equalTo(rightView.mas_left).with.offset(-padding1);//右边距离rightView的左边界-10make.height.mas_equalTo(@150);//高度150make.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的右边界10make.right.equalTo(sv.mas_right).with.offset(-padding1);//右边距离sv的右边界-10make.height.mas_equalTo(@150);//高度150make.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(300300));//将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 ){//创建一个ViewUIView *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递增//判断是否有前一个子Viewif ( lastView ) {//如果有前一个View,上边界和前一个View的下边界紧贴make.top.mas_equalTo(lastView.mas_bottom);} else {//如果没有前一个View,上边界和container的下边界紧贴make.top.mas_equalTo(container.mas_top);}}];//保存前一个ViewlastView = 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哈!
复制代码
src="http://player.youku.com/embed/XNzkxMTc3OTM2" allowfullscreen="" frameborder="0" height="498" width="510">
src="http://player.youku.com/embed/XNzkxMTc3OTM2" allowfullscreen="" frameborder="0" height="498" width="510">

这篇关于iOS学习笔记36-Masonry自动布局的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/868113

相关文章

浏览器插件cursor实现自动注册、续杯的详细过程

《浏览器插件cursor实现自动注册、续杯的详细过程》Cursor简易注册助手脚本通过自动化邮箱填写和验证码获取流程,大大简化了Cursor的注册过程,它不仅提高了注册效率,还通过友好的用户界面和详细... 目录前言功能概述使用方法安装脚本使用流程邮箱输入页面验证码页面实战演示技术实现核心功能实现1. 随机

HTML5实现的移动端购物车自动结算功能示例代码

《HTML5实现的移动端购物车自动结算功能示例代码》本文介绍HTML5实现移动端购物车自动结算,通过WebStorage、事件监听、DOM操作等技术,确保实时更新与数据同步,优化性能及无障碍性,提升用... 目录1. 移动端购物车自动结算概述2. 数据存储与状态保存机制2.1 浏览器端的数据存储方式2.1.

一文详解MySQL如何设置自动备份任务

《一文详解MySQL如何设置自动备份任务》设置自动备份任务可以确保你的数据库定期备份,防止数据丢失,下面我们就来详细介绍一下如何使用Bash脚本和Cron任务在Linux系统上设置MySQL数据库的自... 目录1. 编写备份脚本1.1 创建并编辑备份脚本1.2 给予脚本执行权限2. 设置 Cron 任务2

MyBatis Plus 中 update_time 字段自动填充失效的原因分析及解决方案(最新整理)

《MyBatisPlus中update_time字段自动填充失效的原因分析及解决方案(最新整理)》在使用MyBatisPlus时,通常我们会在数据库表中设置create_time和update... 目录前言一、问题现象二、原因分析三、总结:常见原因与解决方法对照表四、推荐写法前言在使用 MyBATis

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Python使用smtplib库开发一个邮件自动发送工具

《Python使用smtplib库开发一个邮件自动发送工具》在现代软件开发中,自动化邮件发送是一个非常实用的功能,无论是系统通知、营销邮件、还是日常工作报告,Python的smtplib库都能帮助我们... 目录代码实现与知识点解析1. 导入必要的库2. 配置邮件服务器参数3. 创建邮件发送类4. 实现邮件

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

Python使用pynput模拟实现键盘自动输入工具

《Python使用pynput模拟实现键盘自动输入工具》在日常办公和软件开发中,我们经常需要处理大量重复的文本输入工作,所以本文就来和大家介绍一款使用Python的PyQt5库结合pynput键盘控制... 目录概述:当自动化遇上可视化功能全景图核心功能矩阵技术栈深度效果展示使用教程四步操作指南核心代码解析

SpringBoot实现文件记录日志及日志文件自动归档和压缩

《SpringBoot实现文件记录日志及日志文件自动归档和压缩》Logback是Java日志框架,通过Logger收集日志并经Appender输出至控制台、文件等,SpringBoot配置logbac... 目录1、什么是Logback2、SpringBoot实现文件记录日志,日志文件自动归档和压缩2.1、

SpringCloud使用Nacos 配置中心实现配置自动刷新功能使用

《SpringCloud使用Nacos配置中心实现配置自动刷新功能使用》SpringCloud项目中使用Nacos作为配置中心可以方便开发及运维人员随时查看配置信息,及配置共享,并且Nacos支持配... 目录前言一、Nacos中集中配置方式?二、使用步骤1.使用$Value 注解2.使用@Configur