從開始做IOS項(xiàng)目都是xib或者storyboard。都是增加脫線增加約束诽嘉。但是網(wǎng)上很多別人的優(yōu)秀代碼,有些是Masonry約束的。為了學(xué)習(xí)別人的代碼耸三,自己也需要Masonry未舟。
源碼地址 https://github.com/SnapKit/Masonry
需要導(dǎo)入#import "Masonry.h"
例子1
// 初始化view并設(shè)置背景
UIView *view = [UIView new];
view.backgroundColor = [UIColor redColor];
[self.view addSubview:view]; ?//在做autoLayout之前 一定要先將view添加到superview上面术瓮,否則會崩潰
// 使用mas_makeConstraints添加約束
[view mas_makeConstraints:^(MASConstraintMaker *make) {
// 添加大小約束
make.size.mas_equalTo(CGSizeMake(100, 100));
// 添加居中約束(居中方式與self相同)
make.center.equalTo(self.view);
}];
例子2
// 初始化view并設(shè)置背景
UIView *view = [UIView new];
view.backgroundColor = [UIColor redColor];
[self.view addSubview:view];
// 使用mas_makeConstraints添加約束
[view mas_makeConstraints:^(MASConstraintMaker *make) {
// 添加大小約束
make.size.mas_equalTo(CGSizeMake(100, 100));
// 添加居中約束(居中方式與self相同)
make.center.equalTo(self.view);
}];
UIView *view2=[UIView new];
view2.backgroundColor=[UIColor purpleColor];
[view? addSubview:view2];
[view2 mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(view).with.insets(UIEdgeInsetsMake(10, 10, 10, 10));
}];
例子3
// 初始化view并設(shè)置背景
UIView *view11 = [UIView new];
view11.backgroundColor = [UIColor redColor];
[self.view addSubview:view11];
// 使用mas_makeConstraints添加約束
//mas_makeConstraints就是Masonry的autolayout添加函數(shù) 將所需的約束添加到block中行了
[view11 mas_makeConstraints:^(MASConstraintMaker *make) {
//將sv居中(很容易理解吧?)
make.center.equalTo(self.view);
//將size設(shè)置成(300,300)
make.size.mas_equalTo(CGSizeMake(300, 300));
}];
int padding1=10;
UIView *view1=[UIView new];
[view1 showPlaceHolder];
view1.backgroundColor=[UIColor purpleColor];
UIView *view2=[UIView new];
view2.backgroundColor=[UIColor orangeColor];
[view2 showPlaceHolder];
[self.view addSubview:view1];
[self.view addSubview:view2];
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerY.mas_equalTo(view11.mas_centerY);
make.left.equalTo(view11.mas_left).with.offset(padding1);
make.right.equalTo(view2.mas_left).with.offset(-padding1);
make.height.mas_equalTo(@150);
make.width.equalTo(view2);
}];
[view2 mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerY.mas_equalTo(view11.mas_centerY);
make.left.equalTo(view1.mas_right).with.offset(padding1);
make.right.equalTo(view11.mas_right).with.offset(-padding1);
make.height.mas_equalTo(@150);
make.width.equalTo(view1);
}];