我有以下情况:
添加子视图的代码(我尝试调整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看起来像这样:
此代码在日志中没有任何约束错误,并且看起来像预期。
我的问题是: scrollview的内容大小不会改变。我可以添加尽可能多的标签,但滚动永远不会有效。 你能帮我动态扩大我的滚动视图吗?
答案 0 :(得分:1)
如果所有约束都足以在容器视图中定义内部内容大小,则滚动视图-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];
}