Masonry入门介绍
前言
随着iPhone尺寸的变化,由最初的(320,480)到(320,568),再到现在iphone6,iphone6plus,屏幕尺寸不断变化,对于屏幕多样性的支持让我十分苦恼,虽然从iOS6开始,storyboard中新增了autoLayout,但是我平时更喜欢手动布局,所以这个不在我的考虑之列。直到前两天偶然看到Github上一个第三发个库Masonry,并花了几个小时研究,发现autolayout封装的真的不错,下面将这个进行介绍。
介绍
1.安装
按照前面介绍的,首先安装cocoapods。初始化podfile文件:pod init;然后编辑podfile文件,执行pod install。
1 # Uncomment this line to define a global platform for your project
2 platform :ios, '7.0'
3
4 target 'MasonryDemo' do
5 pod 'Masonry', '~> 0.6.1'
6 end
~
2.使用(下面这里大部分都是参考作者里脊串的Masonry,地址:http://adad184.com/2014/09/28/use-masonry-to-quick-solve-autolayout/)
看一下Masonry支持的属性如下:
1 @property (nonatomic, strong, readonly) MASConstraint *left;
2 @property (nonatomic, strong, readonly) MASConstraint *top;
3 @property (nonatomic, strong, readonly) MASConstraint *right;
4 @property (nonatomic, strong, readonly) MASConstraint *bottom;
5 @property (nonatomic, strong, readonly) MASConstraint *leading;
6 @property (nonatomic, strong, readonly) MASConstraint *trailing;
7 @property (nonatomic, strong, readonly) MASConstraint *width;
8 @property (nonatomic, strong, readonly) MASConstraint *height;
9 @property (nonatomic, strong, readonly) MASConstraint *centerX;
10 @property (nonatomic, strong, readonly) MASConstraint *centerY;
11 @property (nonatomic, strong, readonly) MASConstraint *baseline;
举例(居中显示一个view)
//这里不在用CGRectMake了
UIView *sv = [UIView new];
//在Masonry进行autolayout之前,一定要先讲view添加到superview中去
sv.backgroundColor = [UIColor greenColor];
[self.view addSubview:sv];
//mas_makeConstraints就是Masonry的autolayout的函数,将所需的约束添加到block中去
[sv mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(self.view);
make.size.mas_equalTo(CGSizeMake(300, 300));
}];
这样便在view中添加一个子view,位置是居中,大小300X300.
有关Masonry中几个布局的函数下面进行介绍: 1.在Masonry中进行autolayout布局约束的三个函数:
- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block;
- (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block;
- (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block;
/*
mas_makeConstraints 只负责新增约束 Autolayout不能同时存在两条针对于同一对象的约束 否则会报错
mas_updateConstraints 针对上面的情况 会更新在block中出现的约束 不会导致出现两个相同约束的情况
mas_remakeConstraints 则会清除之前的所有约束 仅保留最新的约束
三种函数善加利用 就可以应对各种情况了
*/