当我调整父UIView的大小时,子视图会意外地限制大小更改

时间:2016-07-09 05:11:12

标签: ios objective-c uiview

我以编程方式创建了一个包含两个子视图的父视图。在某些时候,在两个原始子视图之间添加第三个子视图,并相应调整父级的大小:

_childView1 = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0, 320.0, 320.0)];
_childView2 = [[UIView alloc] initWithFrame:CGRectMake(0.0, _childView1.frame.size.height, 320.0, 320.0)];
_parentView = = [[UIView alloc]initWithFrame: CGRectMake(0, 0, self.view.frame.size.width, _childView1.frame.size.height+_childView2.frame.size.height)];
[_parentView addSubview: _childView1];
[_parentView addSubview: _childView2];
[self.view addSubview:_parentView];
...
// Later on...
_childView3 = [[UIView alloc] initWithFrame:CGRectMake(0.0, _childView1.frame.size.height, 320.0, 162)];
[_parentView insertSubview:_childView3 belowSubview: _childView2];

// Resize the parent view
_parentView.frame = CGRectMake(_parentView.frame.origin.x, _parentView.frame.origin.y, _parentView.frame.size.width, _parentView.frame.size.height+_childView3.frame.size.height);
// [_childView1 setFrame:CGRectMake(0.0, 0, 320.0, 320.0)]; // (1)
// [_childView1 setBounds:CGRectMake(0.0, 0, 320.0, 320.0)]; // (2)

[UIView animateWithDuration:0.8 delay:0.0 options:UIViewAnimationOptionRepeat animations:^{
[UIView setAnimationRepeatCount:1];

// Shift the second child view down to accommodate the third view
_childView2.frame = CGRectMake(_childView2.frame.origin.x, _childView2.frame.origin.y+_childView3.frame.size.height+3, _childView2.frame.size.width, _childView2.frame.size.height);
        }completion:nil];

我期待childView1保持锚定到parentView的上边缘,而childView2动画向下滚动。

相反,childView3的bounds.size.height由childView3(320 + 162)增加。这几乎就像在childView1的顶部添加了一些填充。

有趣的是,如果我将childView1的frame.size重置为原始大小而不注释(1),一切都按预期工作。但我不认为这是解决问题的最佳方案。 重置bounds.size(取消注释(2))没有任何改进。

我是否需要禁用一些自动布局设置以将childView1固定到parentView的顶部边框?

0 个答案:

没有答案