[英]Enlarge UIScrollview's content size dynamically when adding views programatically
我有以下情況:
添加子視圖的代碼(以及我嘗試調整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];
}
我的情節提要約束如下所示:
該代碼可以正常工作,日志中沒有任何約束錯誤,看起來像預期的那樣。
我的問題是:scrollview的內容大小不會改變。 我可以添加任意數量的標簽,但滾動永遠行不通。 您能幫我動態放大滾動視圖嗎?
如果所有約束條件都足以在容器視圖中定義固有內容大小,則滾動視圖-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.