iOS自动布局之Masonry第四弹

/ 0评 / 0

这次我们考虑一下子视图跟随父视图变化而变化的做法

/**子随父动的方法**/
- (void)sonViewWithFatherView{
    UIView *greenView = [[UIView alloc] init];
    greenView.backgroundColor = UIColor.greenColor;
    greenView.layer.borderColor = UIColor.blackColor.CGColor;
    greenView.layer.borderWidth = 2;
    [self.view addSubview:greenView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap)
                                   ];
    [greenView addGestureRecognizer:tap];
    self.greenView = greenView;
    
    UIView *blueView = UIView.new;
    blueView.backgroundColor = UIColor.blueColor;
    blueView.layer.borderColor = UIColor.blackColor.CGColor;
    blueView.layer.borderWidth = 2;
    [self.view addSubview:blueView];
    self.blueView = blueView;
    
    
    // 这里,我们不使用updateViewConstraints方法,但是我们一样可以做到。
    // 不过苹果推荐在updateViewConstraints方法中更新或者添加约束的
    [self updateWithExpand:NO animated:NO];
    
    UILabel *label = [[UILabel alloc] init];
    label.numberOfLines = 0;
    label.textColor = [UIColor redColor];
    label.font = [UIFont systemFontOfSize:16];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"点击绿色部分放大,蓝色部分最大值250,最小值90";
    [self.greenView addSubview:label];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
    }];
}

- (void)updateWithExpand:(BOOL)isExpanded animated:(BOOL)animated {
    self.isExpaned = isExpanded;
    
    [self.greenView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        if (isExpanded) {
            make.bottom.mas_equalTo(-20);
        } else {
            make.bottom.mas_equalTo(-300);
        }
    }];
    
    [self.blueView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.greenView);
        
        // 这里使用优先级处理
        // 设置宽高,这里用的连贯操作
        if (!isExpanded) {
            make.width.height.mas_equalTo(100 * 0.5).priorityLow();
        } else {
            make.width.height.mas_equalTo(100 * 3).priorityLow();
        }
        
        // 最大值为250
        make.width.height.lessThanOrEqualTo(@250);
        
        // 最小值为90
        make.width.height.greaterThanOrEqualTo(@90);
    }];
    
    if (animated) {
        [self.view setNeedsUpdateConstraints];
        [self.view updateConstraintsIfNeeded];
        
        [UIView animateWithDuration:0.5 animations:^{
            [self.view layoutIfNeeded];
        }];
    }
}

- (void)onTap {
    [self updateWithExpand:!self.isExpaned animated:YES];
}

当我们没有点击的时候,两个视图都会变大,这里要注意一下:我们没有使用updateViewConstraints方法,但是我们一样做到了。不过苹果推荐在updateViewConstraints方法中更新或者添加约束的

Masonry 009

Masonry 010

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

评论已关闭。