[英]Enlarge UIScrollview's content size dynamically when adding views programatically
I have the following situation: 我有以下情况:
Code for adding childviews (and my try to resize scrollview's content size): 添加子视图的代码(以及我尝试调整scrollview的内容大小的代码):
- (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];
}
My Storyboard Constraints look like this: 我的情节提要约束如下所示:
This code works without any constraint errors in log and it looks like expected. 该代码可以正常工作,日志中没有任何约束错误,看起来像预期的那样。
My problem is: The scrollview's content size doesn't change. 我的问题是:scrollview的内容大小不会改变。 I can add as many labels as I want to, but scrolling never works.
我可以添加任意数量的标签,但滚动永远行不通。 Can you please help me to dynamically enlarge my scrollview?
您能帮我动态放大滚动视图吗?
If all the constraints makes a sufficient set to define an intrinsic content size in the container view, the scroll view -contentSize
should resize accordingly, just need to call -(void)invalidateIntrinsicContentSize
on the scroll view after you added the content. 如果所有约束条件都足以在容器视图中定义固有内容大小,则滚动视图
-contentSize
应该相应地调整大小,只需在添加内容后在滚动视图上调用-(void)invalidateIntrinsicContentSize
。
- (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 invalidateIntrinsicContentSize];
[_scrollView setNeedsLayout];
[_scrollView layoutIfNeeded];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.