項目里經常會需要根據子視圖的高度自動改變父視圖的高度。
簡單舉個例子,綠色區域作為父視圖,紅色區域添加在綠色區域上。
現在讓綠色區域的高度跟着紅色區域的高度來自動改變。
代碼如下
UIView *view = [[UIView alloc]init];
view.backgroundColor = UIColor.greenColor;
[self.view addSubview:view];
contentView *content =[[contentView alloc]init];
content.backgroundColor = UIColor.redColor;
[view addSubview:content];
[view mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.top.equalTo(@100);
make.right.equalTo(@-100);
}];
float contentHeight = [content setHeight];
[content mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.top.equalTo(@50);
make.right.equalTo(@-100);
make.height.mas_equalTo(contentHeight);
make.bottom.equalTo(view.mas_bottom).mas_offset(@-10);
}];
思路:綠色區域view不設置高度。紅色區域 設置高度,並設置底部距離view的底間距
make.bottom.equalTo(view.mas_bottom).mas_offset(@-10);