Masonry

Masonry是一个轻量级的iOS布局框架,简化了NSLayoutConstraint的使用。它通过View+MASAdditions分类提供便利的方法,如mas_makeConstraints,mas_updateConstraints和mas_remakeConstraints。MASViewAttribute封装了UIView和NSLayoutAttribute,而MASViewConstraint是对NSLayoutConstraint的封装,支持链式调用。MASConstraintMaker作为工厂类,负责创建和安装约束。此外,还有UIView+MASConstraints私有类别,用于记录安装的约束。
摘要由CSDN通过智能技术生成

Masonry框架的优点

 

Masonry是iOS在控件布局中经常使用的一个轻量级框架,Masonry让NSLayoutConstraint使用起来更为简洁。

基于NSLayoutConstraint的布局实现subView.top = superView.top * 1 + 10


subView.translatesAutoresizingMaskIntoConstraints = NO;//关闭自动布局
NSLayoutConstraint *constraint= [NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeTop multiplier:1.0f constant:10.0f];
[subView addConstraint:constraint];

基于Masonry的布局实现subView.top = superView.top * 1 + 10


[superView addSubView:subView];//必须先把view添加到父view才能使用Masonry的布局
[subView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(@10);//3种写法
    //make.top.equalTo(superView.mas_top).offset(10);
    //make.top.equalTo(superView.mas_top).multipliedBy(1).offset(10);
}];

可以看到Masonry极大的简化了布局代码,用起来非常方便。

Masonry框架的类结构

1.View+MASAdditions分类介绍(左边红框中的部分)

View+MASAdditions的部分,在该分类中添加了类型为MASViewAttribute的成员属性。


- (MASViewAttribute *)mas_left {
    return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeft];
}
 
- (MASViewAttribute *)mas_top {
    return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTop];
}
······

mas_left = self + NSLayoutAttributeLeft, mas_top = self +NSLayoutAttributeTop, 当然此处的self就代表当前视图。

还添加了3个公有的方法:

  • mas_makeConstraints方法负责创建安装约束

  • mas_updateConstraints负责更新已经存在的约束(若约束不存在就Install)

  • mas_remakeConstraints方法则负责移除原来已经创建的约束并添加上新的约束。

  • //返回一个数组,数组中所存放的就是当前视图中所添加的所有约束。
    - (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *))block {
        //关闭自动添加约束,我们要手动添加约束
        self.translatesAutoresizingMaskIntoConstraints = NO;
        //MASConstraintMaker类是一个工厂类,负责创建MASConstraint类型的对象(依赖于MASConstraint接口,而不依赖于具体实现)。
        MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self];
        //给maker中的成员属性赋值
        block(constraintMaker);
        return [constraintMaker install];
    }
    
    其他两个方法内部的实现与mas_makeConstraints类似,就是多了一个属性的设置。

mas_updateConstraints中将constraintMaker中的updateExisting设置为YES

mas_remakeConstraints中所做的事情是将removeExisting属性设置成YES

2.MASViewAttribute类的介绍(右边黄框中的部分)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值