美文网首页
如何使用Masonry根据子视图size改变父视图size(MB

如何使用Masonry根据子视图size改变父视图size(MB

作者: ZJ_偶尔上路 | 来源:发表于2017-07-27 15:12 被阅读0次
    05B11B7DDD2F608AD10DB48D8D84A419.png

    最近需要做一个近似于MBProgressHUD功能的一个控件,于是就仔细看了看MBProgressHUD的源码。总的来说,它的重点在于HUD初始化、show、hide方法,以及视图的处理方式,但是难点个人认为在于autolayout。它是用系统的约束布局,看起来比较苦涩难懂,除非对系统约束比较熟悉。

    现在大多数项目的布局都是用的第三方布局工具Masonry,我个人也是相对用的比较顺手,重要的是我对系统布局没什么研究,所以在封装控件的时候就用的Masonry。

    如何使用Masonry根据子视图size改变父视图size是这篇文章要解决的问题

    如上图,我想在红色的bgView上放两个UILabel(label、detailLabel),bgView最大width是它的左右边缘距离父视图左右边缘都是20px;两个label的最大width是它的左右边缘距离父视图左右边缘都是10px;bgView的最小size是400px*400px。

    直接上代码吧,仔细想想就可以理解为什么要这样做:

    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        
        [self.view addSubview:self.bgView];
        [self.bgView addSubview:self.label];
        [self.bgView addSubview:self.detailLabel];
        
        [_label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.bgView);
            make.height.mas_equalTo(40);
            make.width.lessThanOrEqualTo(self.bgView).mas_offset(-10);
        }];
        
        [_detailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.bgView);
            make.top.mas_equalTo(_label.mas_bottom).mas_offset(10);
            make.height.mas_equalTo(40);
            make.width.lessThanOrEqualTo(self.bgView).mas_offset(-10);
        }];
        
        [_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.view);
            make.height.mas_equalTo(200);
            make.width.mas_equalTo(200).priorityLow();
            make.width.lessThanOrEqualTo(self.view).mas_offset(-20);
        }];
        
    }
    
    - (UIView *)bgView {
        if (!_bgView) {
            _bgView = [[UIView alloc] init];
            _bgView.backgroundColor = [UIColor redColor];
        }
        return _bgView;
    }
    
    - (UILabel *)label {
        if (!_label) {
            _label = [[UILabel alloc] init];
            _label.textAlignment = NSTextAlignmentCenter;
            _label.text = @"[UIColor brownColor]";
            _label.backgroundColor = [UIColor brownColor];
        }
        return _label;
    }
    
    - (UILabel *)detailLabel {
        if (!_detailLabel) {
            _detailLabel = [[UILabel alloc] init];
            _detailLabel.textAlignment = NSTextAlignmentCenter;
            _detailLabel.text = @"这是detailLabelMBProgressHUDMBProgressHUD";
            _detailLabel.backgroundColor = [UIColor brownColor];
        }
        return _detailLabel;
    }
    
    

    这只是一个例子,举一反三适用于很多场景。

    相关文章

      网友评论

          本文标题:如何使用Masonry根据子视图size改变父视图size(MB

          本文链接:https://www.haomeiwen.com/subject/ayuzkxtx.html