一、使用 frame 来计算父 view 的高度。
- (void)frameCalHeight {
UIView *parentView = [[UIView alloc] init];
parentView.backgroundColor = [UIColor orangeColor];
parentView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 0); // 高度不知道给0
[self.view addSubview:parentView];
UIView *childView = [UIView new];
childView.frame = CGRectMake(0, 20, 300, 300);
childView.backgroundColor = [UIColor redColor];
[parentView addSubview:childView];
CGFloat parentHeight = CGRectGetMaxY(parentView.subviews.lastObject.frame) + 20; // 最大 Y 加一个底部边距20
CGRect frame = parentView.frame;
frame.size.height = parentHeight;
parentView.frame = frame;
运行结果:
父视图的高度不清楚,要由子视图的个数决定,所以一开始的 frame.height = 0
。
在子视图全部利用 frame 布局完成之后,在根据最后一个子视图的 maxY + 可能存在的下边距计算出父视图的 frame.height。
二、使用 autoLayout
UIView *parentView = [[UIView alloc] init];
parentView.backgroundColor = [UIColor orangeColor];
[self.view addSubview:parentView];
[parentView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.top.right.offset(0); // 没有设置高度
UIView *childView1 = [UIView new];
childView1.backgroundColor = [UIColor purpleColor];
[parentView addSubview:childView1];
[childView1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.offset(10); // top = 10
make.left.right.offset(0);
make.height.offset(200); // height = 200
make.bottom.offset(-10); // bottom = 10
// 所以,最终计算的 parentView.height = 200 + 10 + 10 = 220;
最终运行结果: