Masonry(一)

简介

Masonry is still actively maintained, we are committed to fixing bugs and merging good quality PRs from the wider community. However if you’re using Swift in your project, we recommend using SnapKit as it provides better type safety with a simpler API.

Masonry 传送门

使用前的准备

// 对于约束参数可以省去"mas_"
#define MAS_SHORTHAND
// 对于默认的约束参数自动装箱
#define MAS_SHORTHAND_GLOBALS

直接这样

// define this constant if you want to use Masonry without the 'mas_' prefix
#define MAS_SHORTHAND
// define this constant if you want to enable auto-boxing for default syntax
#define MAS_SHORTHAND_GLOBALS

// 宏必须添加在头文件前面
#import "Masonry.h" 

添加约束前提:被约束的必须有父控件,其中约束项都必须是UIView或子类的实例。

约束的三种方法

/**
 // 这个方法只会添加新的约束
 [blueView mas_makeConstraints:^(MASConstraintMaker *make)  {

 }];

 // 这个方法会将以前的所有约束删掉,添加新的约束
 [blueView mas_remakeConstraints:^(MASConstraintMaker *make) {

 }];

 // 这个方法将会覆盖以前的某些特定的约束
 [blueView mas_updateConstraints:^(MASConstraintMaker *make) {

 }];
 */

常见约束的各种类型

/**
 尺寸:width、height、size
 边界:left、leading、right、trailing、top、bottom
 中心点:center、centerX、centerY
 边界:edges
 偏移量:offset、insets、sizeOffset、centerOffset
 priority()约束优先级(0~1000),multipler乘因数, dividedBy除因数
 */

Masonry约束易忽略的技术点

使用Masonry不需要设置控件的translatesAutoresizingMaskIntoConstraints属性为NO;

防止block中的循环引用,使用弱引用(这是错误观点),在这里block是局部的引用,block内部引用self不会造成循环引用的

__weak typeof (self) weakSelf = self;

Masonry约束控件出现冲突的问题

当约束冲突发生的时候,我们可以设置viewkey来定位是哪个view

redView.mas_key = @"redView";

greenView.mas_key = @"greenView";

blueView.mas_key = @"blueView";

若是觉得这样一个个设置比较繁琐,怎么办呢,Masonry则提供了批量设置的宏

MASAttachKeys
MASAttachKeys(redView,greenView,blueView);

约束iconView距离各个边距为30

[iconView makeConstraints:^(MASConstraintMaker *make) {
      make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(30, 30, 30, 30));
    }];

equalTo 和 mas_equalTo的区别

#define mas_equalTo(...) equalTo(MASBoxValue((__VA_ARGS__)))
#define mas_greaterThanOrEqualTo(...) greaterThanOrEqualTo(MASBoxValue((__VA_ARGS__)))
#define mas_lessThanOrEqualTo(...) lessThanOrEqualTo(MASBoxValue((__VA_ARGS__)))
#define mas_offset(...) valueOffset(MASBoxValue((__VA_ARGS__)))

得出结论:mas_equalTo只是对其参数进行了一个BOX(装箱) 操作,目前支持的类型:数值类型(NSNumber)、 点(CGPoint)、大小(CGSize)、边距(UIEdgeInsets),而equalTo这个方法不会对参数进行包装。

[iconView makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-30);
        make.top.equalTo(self.view).offset(30);
        make.height.width.equalTo(100); //== make.size.equalTo(100);
        // make.size.mas_equalTo(self.view).multipliedBy(0.5);
        // make.top.greaterThanOrEqualTo(self.view).offset(padding);
    }];
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
        // with 增强可读性
        make.top.equalTo(superview.mas_top).with.offset(10);  
        // and 增强可读性
        make.left.equalTo(greenView.mas_right).and.offset(10);
        make.bottom.equalTo(blueView.mas_top).offset(-10);
        make.right.equalTo(superview.mas_right).offset(-10);
        make.width.equalTo(greenView.mas_width);
        // 约束参数相同可以通过数组
        make.height.equalTo(@[greenView, blueView]); 
    }];

更新约束的问题

  • 监听按钮点击
[self.btn addTarget:self action:@selector(didClickBtn:) forControlEvents:UIControlEventTouchUpInside];
  • 处理事件
- (void)didClickBtn:(UIButton *)button {
  // 设置一个属性(btnSize)保存其大小的变化
  self.btnSize = CGSizeMake(self.btnSize.width * 1.3, self.btnSize.height * 1.3); 
  // 告知需要更新约束,但不会立刻开始,系统然后调用updateConstraints
  [self setNeedsUpdateConstraints];
  // 告知立刻更新约束,系统立即调用updateConstraints
  [self updateConstraintsIfNeeded];
  // 这里动画当然可以取消,具体看项目的需求
  // 系统block内引用不会导致循环引用,block结束就会释放引用对象
  [UIView animateWithDuration:0.4 animations:^{
      // 告知页面立刻刷新,系统立即调用updateConstraints
      [self layoutIfNeeded]; 
  }];
}
  • 苹果官方建议:添加/更新约束在这个方法(updateConstraints)内
// this is Apple's recommended place for adding/updating constraints
- (void)updateConstraints {
   // 更新约束
    [self.btn updateConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.equalTo(@(self.buttonSize.width)).priorityLow();
        make.height.equalTo(@(self.buttonSize.height)).priorityLow();
        make.width.lessThanOrEqualTo(self);
        make.height.lessThanOrEqualTo(self);
    }];
    // according to apple super should be called at end of method
    // 最后必须调用父类的更新约束
    [super updateConstraints];
}
  • 设置requiresConstraintBasedLayout为YES
+ (BOOL)requiresConstraintBasedLayout {
    // 重写这个方法 若视图基于自动布局的
    return YES ; 
}

重置约束的问题

对于控件的重新约束,则之前的约束都是无效的,步骤都更新约束一样的,只是在updateConstraints方法内的约束方法改为了remakeConstraints,直接贴代码吧(仍以按钮为例,其他原理都是相同的)

// 首先监听按钮
[self.btn addTarget:self action:@selector(didClickBtn:) forControlEvents:UIControlEventTouchUpInside];
// 处理事件
- (void)didClickBtn:(UIButton *)button {
   (...) // 触发条件
    [self setNeedsUpdateConstraints]; 
    [self updateConstraintsIfNeeded];
   /**
     *   动画展示变化 - 这句代码可有可无,参考项目具体的需求
     *   [UIView animateWithDuration:0.4 animations:^{
     *         [self layoutIfNeeded];
     *   }];
     */
}

// 重置约束
- (void)updateConstraints {
    [self.btn remakeConstraints:^(MASConstraintMaker *make) {
      .....
    }];
    [super updateConstraints]; 
}

+ (BOOL)requiresConstraintBasedLayout{
    // 重写这个方法 若视图基于自动布局的
    return YES ; 
}

多个(2个以上)控件的等间隔排序显示

2个函数

/**
     *  axisType         轴线方向
     *  fixedSpacing     间隔大小
     *  fixedItemLength  每个控件的固定长度/宽度
     *  leadSpacing      头部间隔
     *  tailSpacing      尾部间隔
     *
     */
// 等间隔排列 - 多个控件间隔固定,控件长度/宽度变化
- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType
                    withFixedSpacing:(CGFloat)fixedSpacing 
                         leadSpacing:(CGFloat)leadSpacing
                         tailSpacing:(CGFloat)tailSpacing;

// 等间隔排列 - 多个固定大小固定,间隔空隙变化
- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType
                 withFixedItemLength:(CGFloat)fixedItemLength
                         leadSpacing:(CGFloat)leadSpacing
                         tailSpacing:(CGFloat)tailSpacing;
// 首先添加5个视图
NSMutableArray *array = [NSMutableArray new];
for (int i = 0; i < 5; i ++) {
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor greenColor];
    [self addSubview:view];
    // 保存添加的控件
    [array addObject:view];
}

// 水平方向控件间隔固定等间隔
[array mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:15 leadSpacing:10 tailSpacing:10];
            [array makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(50);
                make.height.equalTo(70);
            }];

// 水平方向宽度固定等间隔
[array mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedItemLength:70 leadSpacing:10 tailSpacing:10];
            [array makeConstraints:^(MASConstraintMaker *make) { 
                // 数组额你不必须都是view 
                make.top.equalTo(50);
                make.height.equalTo(70);
            }];

水平方向等间隔.png

水平方向控件宽度固定等间隔.png

多行label的约束问题

// 创建label
self.label = [UILabel new];
self.label.numberOfLines = 0;
self.label.lineBreakMode = NSLineBreakByTruncatingTail;
self.label.text = @"有的人,没事时喜欢在朋友圈里到处点赞,东评论一句西评论一句,比谁都有存在感。等你有事找他了,他就立刻变得很忙,让你再也找不着。真正的朋友,平常很少联系。可一旦你遇上了难处,他会立刻回复你的消息,第一时间站出来帮你。所谓的存在感,不是你有没有出现,而是你的出现有没有价值。存在感,不是刷出来的,也不是说出来的。有存在感,未必是要个性锋芒毕露、甚至锋利扎人。翩翩君子,温润如玉,真正有存在感的人,反而不会刻意去强调他的存在感。他的出现,永远都恰到好处。我所欣赏的存在感,不是长袖善舞巧言令色,而是对他人的真心关照;不是锋芒毕露计较胜负,而是让人相处得舒服;不是时时刻刻聒噪不休,而是关键时刻能挺身而出。别总急着出风头,希望你能有恰到好处的存在感。";
[self addSubview: self.label];

[self.label makeConstraints:^(MASConstraintMaker *make) {
    make.left.top.equalTo(10);
    make.right.equalTo(-10);
}];

// 添加约束
- (void)layoutSubviews {
    // 执行 [super layoutSubviews];
    [super layoutSubviews];
    // 设置preferredMaxLayoutWidth: 多行label约束的完美解决
   self.label.preferredMaxLayoutWidth = [UIScreen mainScreen].bounds.size.width - 20;
    // 设置preferredLayoutWidth后,需要再次执行 [super layoutSubviews]; 
    // 其实在实际中这步不写,也不会出错,官方解释是说设置preferredLayoutWidth后需要重新计算并布局界面,所以这步最好执行
    [super layoutSubviews];
}

多行label约束.png

UIScrollView

原理同自动布局一样UIScrollView上添加UIView
UIView上添加需要显示的控件UIScrollView滚动高度取决于显示控件的总高度
对子控件做好约束,可达到控制UIView的大小

    // 创建滚动视图
    UIScrollView *scrollView = [UIScrollView new];
    self.scrollView = scrollView;

    scrollView.backgroundColor = [UIColor grayColor];
    [self addSubview:scrollView];

    [self.scrollView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    // 添加内容视图
    [self setUpContentView]; 

- (void)setUpContentView {
    // 约束UIScrollView上contentView
    UIView *contentView = [UIView new];
    [self.scrollView addSubview:contentView];

    [contentView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        // 此处必填 - 关键点
        make.width.equalTo(self.scrollView); 
    }];

    // 添加控件到contentView,约束原理与自动布局相同
    UIView *lastView;
    CGFloat height = 30;
    for (int i = 0; i <1 5; i ++) {
        UIView *view = UIView.new;
        view.backgroundColor = [UIColor colorWithRed:arc4random() % 255 / 256.0  green:arc4random() % 255 / 256.0 blue:arc4random() % 255 / 256.0 alpha:1.0];
        [contentView addSubview:view];

        [view makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(lastView ? lastView.bottom : @0);
            make.left.equalTo(0);
            make.width.equalTo(contentView.width);
            make.height.equalTo(height);
        }];

        height += 30;
        lastView = view;
    }

    [contentView makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(lastView.bottom);
    }];
}

scrollView的约束设置.png

原文链接

猜你喜欢

转载自blog.csdn.net/jichunw/article/details/80222279