簡體   English   中英

以編程方式添加視圖時,動態放大UIScrollview的內容大小

[英]Enlarge UIScrollview's content size dynamically when adding views programatically

我有以下情況:

  • 有一個孩子的UIScrollView(“ _scrollView”):UIView
  • UIView(“ _layoutContainer”)的子視圖數未知
  • UIView的childView以編程方式添加,並且其約束以編程方式設置。

添加子視圖的代碼(以及我嘗試調整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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM