Masonry分析

2018-03-22  本文已影响0人  杰boy

iOS 源代码分析----Masonry

Masonry是OC自动布局的框架,简化了AutoLayout的写法。

Autolayout代码写起来比较繁琐
下面是Autolayout设置上左宽高

//添加 top 约束
NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem: label attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:64];
[self.view addConstraint:topConstraint];

// 添加 left 约束
NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem: label attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0];
[self.view addConstraint:leftConstraint];

// 添加 width 约束
NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem: label attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:200]; 
[label addConstraint:widthConstraint];
    
// 添加 height 约束
NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem: label attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:20];
[label addConstraint:heightConstraint];

Masonry代码使用比较简洁
下面是Masonry设置上左宽高

[label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@64);
        make.left.equalTo(@0);
        make.width.equalTo(@200);
        make.height.equalTo(@20);
    }];

Masonry常用的方法

1.添加约束常用的方法

- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *))block;

2.更新和重新设置约束方法

- (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *))block;
- (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block;

第一个方法 mas_updateConstraints 更新约束、同事可以添加新的约束
第二个方法 mas_remakeConstraints 重置约束 把之前的约束全部删掉

  1. multipliedBy属性 约束值为约束对象的百分比
//宽度为self.view宽度的20%
make.width.equalTo(self.view).multipliedBy(0.2);

4.其他的属性
Masonry有三种关系:等于(.equalTo)、小于(.lessTahnOrEqualTo)、大于(.greaterThanOrEqualTo)

/**
 1.尺寸:width、height、size
 2.边界:left、leading、right、trailing、top、bottom
 3.中心点:center、centerX、centerY
 4.边界:edges
 5.偏移量:offset、insets、sizeOffset、centerOffset
 6.priority()约束优先级(0~1000),multipler乘因数, dividedBy除因数
 */
//设置view的各个边距为30
[view makeConstraints:^(MASConstraintMaker *make) {
      make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(30, 30, 30, 30));
 }];

5.使用Masonry时block内部引用self不会造成循环引用, translatesAutoresizingMaskIntoConstraints也不用设置

使用Masonry不需要设置控件的translatesAutoresizingMaskIntoConstraints属性为NO;
防止block中的循环引用,使用弱引用(这是错误观点),在这里block是局部的引用,block内部引用self不会造成循环引用的
__weak typeof (self) weakSelf = self;(没必要的写法)

上一篇下一篇

猜你喜欢

热点阅读