Reputation: 2916
I have the following situation:
Code for adding childviews (and my try to resize scrollview's content size):
- (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. I can add as many labels as I want to, but scrolling never works. Can you please help me to dynamically enlarge my scrollview?
Upvotes: 0
Views: 374
Reputation: 26385
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.
- (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];
}
Upvotes: 1