2015-12-17 69 views
0

我有以下情況:放大UIScrollView的內容大小時動態編程

  • 的UIScrollView( 「_scrollView」)有一個孩子:UIView的
  • 的UIView( 「_layoutContainer」)有數目不詳childViews的
  • UIView的childView以編程方式添加,並且它們的約束以編程方式設置。

代碼添加childviews(和我嘗試調整滾動視圖的內容的大小):

- (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]; 
} 

我的故事板約束是這樣的:

Constraints in Storyboard

此代碼的工作沒有任何約束日誌中的錯誤,它看起來像預期的。

我的問題是: scrollview的內容大小沒有改變。我可以添加儘可能多的標籤,但是滾動從不起作用。 你能幫我動態放大我的滾動視圖嗎?

回答

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]; 
} 
+0

不起作用。 如果我在添加完所有視圖後記錄了_layoutContainer大小,我仍然會得到{{0,0},{1024,768}}。我認爲scrollView裏面的視圖沒有更新。再測試一下.. –

+0

好吧,試試看:不要在循環中調用-layoutIfNeeded,在循環之後對容器視圖指定-setNeedsLayout然後再調用-layoutIfNeeded。您應該總是將視圖標記爲需要佈局,否則佈局引擎將跳過它。我更新了答案 – Andrea

+0

做了它(並更新了我的問題中的代碼)。不幸的是它沒有改變任何東西。 –