各位童鞋,如果我哪里观点有误,请及时拍砖,不要误导更多的同学们。
上一篇我们简单介绍了一下Masonry的基本属性,相信大家已经看到了Masonry的方便之处,那么我们这一篇简单介绍一下Masonry的常用方法。
//给视图添加新的约束
- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block;
//给视图更新约束
- (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block;
//删除原有所有约束,添加新的约束
- (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block;
这三个算是最常用的方法了,我们也从这3个方法入手,写几个例子,熟悉一下。
No 1: 创建一个左右上下边距10的视图
//父视图
UIView *superview = self.view;
//我们添加的第一个视图
UIView *view1 = [[UIView alloc] init];
view1.backgroundColor = [UIColor blackColor];
/**
* 添加约束之前,必须先把视图添加到父视图当中
* 相当于给视图找一个参照物,约束才知道怎么加
*/
[superview addSubview:view1];
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
/**
* 第一种方式
* with 可用可不用
* mas_equalTo = equealTo
*/
make.left.equalTo(superview).with.offset(10);
make.right.equalTo(superview).with.offset(-10);
make.top.mas_equalTo(superview).with.offset(10);
make.bottom.equalTo(superview).offset(-10);
/*
//第二种方式
make.edges.equalTo(superview).insets(UIEdgeInsetsMake(10, 10, 10, 10));
//第三种方式
make.left.top.right.bottom.equalTo(superview).insets(UIEdgeInsetsMake(10, 10, 10, 10));
*/
}];

No 2:在view1添加一个中心视图,大小为宽200,高200
UIView *view2 = [[UIView alloc]init];
view2.backgroundColor = [UIColor redColor];
[view1 addSubview:view2];
[view2 mas_makeConstraints:^(MASConstraintMaker *make) {
//center : 视图中心点
make.center.equalTo(view1);
/**
* 这里要注意一下为什么用mas_equalTo!!
* MASBoxValue,对参数进行了一个装箱操作
*/
make.size.mas_equalTo(CGSizeMake(200, 200));
}];

No 3:在View2添加两个同宽边距为10的视图
[view3 mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(view2).with.offset(10);
make.top.equalTo(view2).with.offset(10);
make.bottom.equalTo(view2).with.offset(-10);
make.right.equalTo(view4.mas_left).with.offset(-10);
//和View4同宽
make.width.equalTo(view4.mas_width);
}];
[view4 mas_makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(view2).with.offset(-10);
make.top.equalTo(view2).with.offset(10);
make.bottom.equalTo(view2).with.offset(-10);
make.left.equalTo(view3.mas_right).with.offset(10);
make.width.equalTo(view3.mas_width);
}];

简单的一些功能,我们写出来了, 下一篇我们通过masonry来做一个复杂的。同学们多联系啊!
网友评论