2015-12-17 152 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

做了它(并更新了我的问题中的代码)。不幸的是它没有改变任何东西。 –