浅谈 Masonry 布局框架

来源:互联网 发布:java堆排序 编辑:程序博客网 时间:2024/05/17 23:22

Masonry 是一个轻量级的布局框架,拥有自己的描述语法,采用更优雅的链式语法封装自动布局,简洁明了并具有高可读性,而且同时支持 iOS 和 Max OS X。Masonry 是一个用代码写 iOS 或 OS 界面的库,可以代替 Auto layout。

Masonry 使用注意点

  1. 使用 mas_makeConstraints 方法的元素必须事先添加到父元素的中,例如 [self.view addSubview:view];

  2. masequalTo 和 equalTo 区别:masequalTo 比equalTo多了类型转换操作,一般来说,大多数时候两个方法都是 通用的,但是对于数值元素使用mas_equalTo。对于对象或是多个属性的处理,使用equalTo。特别是多个属性时,必须使用equalTo,例如 make.left.and.right.equalTo(self.view);

  3. 注意到方法with和and,这连个方法其实没有做任何操作,方法只是返回对象本身,这这个方法的左右完全是为了方法写的时候的可读性 。make.left.and.right.equalTo(self.view);和make.left.right.equalTo(self.view);是完全一样的,但是明显的加了and方法的语句可读性 更好点。

Masonry 实例讲解

1. 中心点与 self.view 相同,宽高为 250*250

UIView *view = [[UIView alloc] init];    [view setBackgroundColor:[UIColor redColor]];    [self.view addSubview:view];    [view mas_makeConstraints:^(MASConstraintMaker *make) {        make.center.equalTo(self.view);        make.size.mas_equalTo(CGSizeMake(250, 250));    }];

这里写图片描述

2. 矩形上下左右边距都为20

UIView *view = [[UIView alloc] init];    [view setBackgroundColor:[UIColor redColor]];    [self.view addSubview:view];    [view mas_makeConstraints:^(MASConstraintMaker *make) {        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(20, 20, 20, 20));    }];

这里写图片描述

3. 两个高度为150的view垂直居中且等宽且等间隔排列间隔为10

UIView *view1 = [[UIView alloc] init];    [view1 setBackgroundColor:[UIColor redColor]];    [self.view addSubview:view1];    UIView *view2 = [[UIView alloc] init];    [view2 setBackgroundColor:[UIColor redColor]];    [self.view addSubview:view2];    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {        make.centerY.mas_equalTo(self.view.mas_centerY);        make.height.mas_equalTo(150);        make.width.mas_equalTo(view2.mas_width);        make.left.mas_equalTo(self.view.mas_left).with.offset(10);        make.right.mas_equalTo(view2.mas_left).offset(-10);    }];    [view2 mas_makeConstraints:^(MASConstraintMaker *make) {        make.centerY.mas_equalTo(self.view.mas_centerY);        make.height.mas_equalTo(150);        make.width.mas_equalTo(view1.mas_width);        make.left.mas_equalTo(view1.mas_right).with.offset(10);        make.right.equalTo(self.view.mas_right).offset(-10);    }];

这里写图片描述

更多 Masonry 高级布局技巧会在后续博文中与大家分享!

3 0
原创粉丝点击