尽量简单的写,不煽情不感悟!
Masonry是一个轻量级的布局框架 拥有自己的描述语法 采用更优雅的链式语法封装自动布局 简洁明了 并具有高可读性 而且同时支持 iOS 和 Max OS X。
gitHub的链接地址:https://github.com/SnapKit/Masonry
注意几点就行:1.在对subView进行masonry布局之前需要先 进行addsubView操作:如([self.view addsubView:subView]),否则会崩溃!
2.masonry的布局中,left 和 leading(right和trailing)均是对view布局效果一样,但是不能混用,否则在iOS8上会崩溃!
3.masonry是纯代码布局,一般不建议与xib/storyboard上的布局进行混合,否则可能会达不到想要的布局效果,后期查代码时可能也 无法定位!
///直接上代码!
- (void)demo_Masonry {
UIView *left_view = ({
UIView *view = [[UIViewalloc] init];
view.backgroundColor = [UIColorredColor];
[self.viewaddSubview:view];
view;
});
UIView *mid_View = ({
//初始化设置frame在masonry布局后将无效
UIView *view = [[UIViewalloc] initWithFrame:CGRectMake(0,0, 100, 100)];
view.backgroundColor = [UIColorcolorWithRed:1.000green:1.000blue:0.000 alpha:0.510];
view.layer.cornerRadius =50;
view.layer.masksToBounds =YES;
[self.viewaddSubview:view];
//mid_View 在self.view居中
[view mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(self.view);
make.height.width.offset(100);//make.height.width.offset(@(20));
/*
*分开写法,//初学者建议不用缩写
make.height.offset(100);
make.width.offset(100);
*/
}];
UILabel *label = [[UILabelalloc] initWithFrame:CGRectZero];
label.text = @"center";
label.textAlignment =NSTextAlignmentCenter;
label.textColor = [UIColorblackColor];
[view addSubview:label];
//label在view居中
[label mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(view);
}];
view;
});
UIView *right_view = ({
UIView *view = [[UIViewalloc] init];
view.backgroundColor = [UIColorcolorWithRed:1.000green:0.324blue:0.797 alpha:1.000];
[self.viewaddSubview:view];
view;
});
//left_view mid_View right_view autolayout
[left_view mas_makeConstraints:^(MASConstraintMaker *make) {
//距离屏幕左边距离15px
make.leading.equalTo(self.view).offset(15);
//left_view右边距离mid_View左边15,注意为-15
make.trailing.equalTo(mid_View.mas_leading).offset(-15);
//left_view mid_View处于同一高度
make.centerY.equalTo(mid_View.mas_centerY);
//left_view的高.宽设置为100
make.height.offset(100);
//不用设置宽度,让宽度随着整体布局自动变化
}];
[right_view mas_makeConstraints:^(MASConstraintMaker *make) {
make.leading.equalTo(mid_View.mas_trailing).offset(15);//right_view左边距离mid_view右边15px
make.trailing.equalTo(self.view).offset(-15);//right_view右边距离mid_view右边15px
make.centerY.equalTo(mid_View);//make.centerY.equalTo(mid_View.mas_centerY);
make.height.width.offset(100);
}];
//或者使用UIEdgeInsets
UIView *left_subView = [[UIViewalloc] initWithFrame:CGRectZero];
left_subView.backgroundColor = [UIColorblackColor];
left_subView.layer.cornerRadius =5.0;
[left_view addSubview:left_subView];
UIEdgeInsets padding = UIEdgeInsetsMake(25, 25, 25, 25);
[left_subView mas_makeConstraints:^(MASConstraintMaker *make) {
//left_subView 在left_subView内,距离上下左右分别5px
make.edges.equalTo(left_view).width.insets(padding);
}];
[self.viewlayoutIfNeeded];//必要时刷新界面ui布局
}
//效果图