iOS自动布局之Masonry第五弹

/ 0评 / 0

这次来说一下multipliedBy的用法,

    // Create views
    UIView *topView = [[UIView alloc] init];
    topView.backgroundColor = [UIColor redColor];
    [self.view addSubview:topView];
    
    UIView *topInnerView = [[UIView alloc] init];
    topInnerView.backgroundColor = [UIColor greenColor];
    [topView addSubview:topInnerView];
    
    UIView *bottomView = [[UIView alloc] init];
    bottomView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:bottomView];
    
    UIView *bottomInnerView = [[UIView alloc] init];
    bottomInnerView.backgroundColor = [UIColor blueColor];
    [bottomView addSubview:bottomInnerView];
    
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.height.mas_equalTo(bottomView);
    }];
    
    // width = height / 3
    [topInnerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(topView);
        //这是最关键的代码,使用multipliedBy必须是对同一个控件本身,比如,上面的代码中,我们都是对bottomInnerView.mas_width本身的,如果修改成相对于其它控件,会出问题。
        make.width.mas_equalTo(topInnerView.mas_height).multipliedBy(3);
        make.center.mas_equalTo(topView);
        
        // 设置优先级
        make.width.height.mas_equalTo(topView).priorityLow();
        make.width.height.lessThanOrEqualTo(topView);
    }];
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(topView);
        make.top.mas_equalTo(topView.mas_bottom);
    }];
    
    // width/height比为1/3.0,要求是同一个控件的属性比例
    [bottomInnerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(bottomView);
        make.center.mas_equalTo(bottomView);
        // 注意,这个multipliedBy的使用只能是设置同一个控件的,比如这里的bottomInnerView,
        // 设置高/宽为3:1
        make.height.mas_equalTo(bottomInnerView.mas_width).multipliedBy(3);
        
        make.width.height.mas_equalTo(bottomView).priorityLow();
        make.width.height.lessThanOrEqualTo(bottomView);
    }];

这里用到这个其实就是设置宽高比,就比如 例子中的 bottomInnerView ,我们想让它的高宽比为3:1,那我们首先设置其top和bottom与父视图一致且始终在父视图中居中显示,然后我们通过make.width.height.lessThanOrEqualTo设置了宽、高的最大值与父视图相同,然后设置了宽和高与父视图相等,但是优先级为最低,以保证子视图的宽高不超过父视图,最后,我们设置了bottomInnerView的高为宽的3倍。 make.height.mas_equalTo(bottomInnerView.mas_width).multipliedBy(3)

Masonry 011

代码请查看 http://git.oschina.net/zcb1603999/DCTest

评论已关闭。