国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > 综合技术 > Masonry介绍与使用实践:快速上手Autolayout

Masonry介绍与使用实践:快速上手Autolayout

来源:程序员人生   发布时间:2016-07-04 09:11:42 阅读次数:2266次
1
MagicNumber -> autoresizingMask -> autolayout

以上是纯手写代码所经历的关于页面布局的3个时期

在iphone1-iphone3gs时期 window的size固定为(320,480) 我们只需要简单计算1下相对位置就行了

在iphone4-iphone4s时期 苹果推出了retina屏 但是给了码农们非常大的福利:window的size不变

在iphone5-iphone5s时期 window的size变了(320,568) 这时候autoresizingMask派上了用处(为啥这时候候不用Autolayout? 由于还要支持ios5呗) 简单的适配1下便可

在iphone6+时期 window的width也产生了变化(相对5和5s的屏幕比例没有变化) 终究是时候抛弃autoresizingMask改用autolayout了(不用支持ios5了 相对屏幕适配的多样性来讲autoresizingMask也已过时了)

那如何快速的上手autolayout呢? 说实话 当年ios6推出的同时新增了autolayout的特性 我看了1下官方文档和demo 就立马抛弃到1边了 由于实在过于的繁琐和啰嗦(有过经验的朋友肯定有同感)

直到iPhone6发布以后 我知道使用autolayout势在必行了 这时候想起了之前在阅读Github看到过的1个第3方库Masonry 在花了几个小时的研究使用后 我就将autolayout掌握了(重点是我并没有学习任何的官方文档或其他的关于autolayout的知识) 这就是我为何要写下这篇文章来推荐它的缘由.

介绍

Masonry 源码:https://github.com/Masonry/Masonry

Masonry是1个轻量级的布局框架 具有自己的描写语法 采取更优雅的链式语法封装自动布局 简洁明了 并具有高可读性 而且同时支持 iOS 和 Max OS X。

我们先来看1段官方的sample code来认识1下Masonry

1
2
3
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
    make.edges.equalTo(superview).with.insets(padding);
}];

看到block里面的那句话: make edges equalTo superview with insets

通过链式的自然语言 就把view1给autolayout好了 是否是简单易懂?

使用

看1下Masonry支持哪1些属性

1
2
3
4
5
6
7
8
9
10
11
@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的对比表以下

43.jpg

其中leading与left trailing与right 在正常情况下是等价的 但是当1些布局是从右至左时(比如阿拉伯文?没有类似的经验) 则会对调 换句话说就是基本可以不理不用 用left和right就行了

在ios8发布后 又新增了1堆奇奇怪怪的属性(有兴趣的朋友可以去瞅瞅) Masonry暂时还不支持(不过你要支持ios6,ios7 就没必要去管那末多了)

在讲实例之前 先介绍1个MACRO

1
#define WS(weakSelf)  __weak __typeof(&*self)weakSelf = self;

快速的定义1个weakSelf 固然是用于block里面啦 下面进入正题(为了方便 我们测试的superView都是1个size为(300,300)的UIView)

下面 通过1些简单的实例来简单介绍如何轻松愉快的使用Masonry:

1. [基础] 居中显示1个view

1
2
3
4
5
6
7
8
9
10
11
12
13
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生