0
我有以下情况:放大UIScrollView的内容大小时动态编程
- 的UIScrollView( “_scrollView”)有一个孩子:UIView的
- 的UIView( “_layoutContainer”)有数目不详childViews的
- UIView的childView以编程方式添加,并且它们的约束以编程方式设置。
代码添加childviews(和我尝试调整滚动视图的内容的大小):
- (void)viewDidLoad {
[super viewDidLoad];
UIView* lastLabel = _topCollectionView;
for (int i = 0; i<50; i++) {
UILabel* imageLabelView = [UILabel new];
imageLabelView.translatesAutoresizingMaskIntoConstraints = NO;
[_layoutContainer addSubview:imageLabelView];
[_layoutContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(10)-[labelview]-(10)-|" options:0 metrics:nil views:@{@"labelview":imageLabelView}]];
[_layoutContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[previousLabel]-(10)-[imagelabel(40)]" options:0 metrics:nil views:@{@"previousLabel":lastLabel, @"imagelabel":imageLabelView}]];
imageLabelView.text = @"DUMMY";
lastLabel = imageLabelView;
}
[_layoutContainer setNeedsLayout];
[_layoutContainer layoutIfNeeded];
_scrollView.contentSize = _layoutContainer.frame.size;
[_scrollView invalidateIntrinsicContentSize];
}
我的故事板约束是这样的:
此代码的工作没有任何约束日志中的错误,它看起来像预期的。
我的问题是: scrollview的内容大小没有改变。我可以添加尽可能多的标签,但是滚动从不起作用。 你能帮我动态放大我的滚动视图吗?
不起作用。 如果我在添加完所有视图后记录了_layoutContainer大小,我仍然会得到{{0,0},{1024,768}}。我认为scrollView里面的视图没有更新。再测试一下.. –
好吧,试试看:不要在循环中调用-layoutIfNeeded,在循环之后对容器视图指定-setNeedsLayout然后再调用-layoutIfNeeded。您应该总是将视图标记为需要布局,否则布局引擎将跳过它。我更新了答案 – Andrea
做了它(并更新了我的问题中的代码)。不幸的是它没有改变任何东西。 –