iOS Masonry(约束)的基本使用

来源:互联网 发布:手机怎么隐藏网络 编辑:程序博客网 时间:2024/06/05 18:20

一、简介

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

Masonry支持的一些属性

//左侧@property (nonatomic, strong, readonly) MASConstraint *left;//上侧@property (nonatomic, strong, readonly) MASConstraint *top;//右侧@property (nonatomic, strong, readonly) MASConstraint *right;//下侧@property (nonatomic, strong, readonly) MASConstraint *bottom;//顶部@property (nonatomic, strong, readonly) MASConstraint *leading;//底部@property (nonatomic, strong, readonly) MASConstraint *trailing;//宽@property (nonatomic, strong, readonly) MASConstraint *width;//高@property (nonatomic, strong, readonly) MASConstraint *height;//横向中点@property (nonatomic, strong, readonly) MASConstraint *centerX;//纵向中点@property (nonatomic, strong, readonly) MASConstraint *centerY;//文本基线@property (nonatomic, strong, readonly) MASConstraint *baseline;

二、基本使用

1、创建一个坐标为(100,100),宽度100,高度100的view:

    UIView *view = [UIView new];    view.backgroundColor = [UIColor orangeColor];    [self.view addSubview:view];    //在做autoLayout之前 一定要先将view添加到superview上 否则会报错    [view mas_makeConstraints:^(MASConstraintMaker *make) {        make.left.equalTo(@100);        make.top.equalTo(@100);        make.width.equalTo(@100);        make.height.equalTo(@100);    }];

2、创建一个位于屏幕中央,宽度100,高度100的view:

    UIView *view = [UIView new];    view.backgroundColor = [UIColor orangeColor];    [self.view addSubview:view];    [view mas_makeConstraints:^(MASConstraintMaker *make) {        make.width.equalTo(@100);        make.height.equalTo(@100);        make.center.mas_equalTo(view.center);    }];

3、创建一个与屏幕四边间隔都为10的view:

    UIView *view = [UIView new];    view.backgroundColor = [UIColor orangeColor];    [self.view addSubview:view];    [view mas_makeConstraints:^(MASConstraintMaker *make) {        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(10, 10, 10, 10));    }];

三、特别说明

在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 则会清除之前的所有约束 仅保留最新的约束三种函数善加利用 就可以应对各种情况了*/
0 0