2017-07-07 69 views
1

我创建使用Swift3一个应用程序,和我有困难的正确定义高度UIScrollView,我使用autolayout创建此结构:正确地定义高度的UIScrollView

  • UIScrollView
    • UIView //集装箱view
    • UIImageView // Constraint顶部边缘= 20与UIView
    • UITextView // Constraint顶部边缘相= 40到相对于UIImageView
    • UITextView // Constraint顶部边缘= 20〜UITextView
    • UIButtonConstraint //顶部相边线30至UITextView

目前,我使用此逻辑来计算UIScrollView高度

override func viewDidLayoutSubviews() { 
    var scrollHeight : CGFloat = 0.0 

    for view in self.containerView.subviews { 
     view.layoutIfNeeded() 
     scrollHeight += view.frame.size.height 
    } 

    // Adding height for scrollview, according to the sum of all child views 
    self.scrollView.contentSize.height = scrollHeight 

} 

但是,我只能得到views高度,他们不考虑Constraints“利润”,我想知道有什么办法按照自己的内容来计算正确的高度为UIScrollView,调整。

+0

如果您将最后一个按钮的约束添加到滚动视图的底部,您应该手动设置内容的大小。 – agibson007

+0

@ agibson007但我没有添加这个约束,只在上面的UI视图底部添加约束 –

+1

是的,这就是我的意思是抱歉。这应该工作。看到我刚才给出的答案。 https://stackoverflow.com/questions/42684594/ios-uiscrollview-with-dynamic-content-using-containerview-step-by-step/42685952#42685952 – agibson007

回答

0

关闭!让我们为每个视图添加顶部边距:

override func viewDidLayoutSubviews() { 
    var scrollHeight : CGFloat = 0.0 

    for view in self.containerView.subviews { 
     view.layoutIfNeeded() 
     scrollHeight += view.frame.size.height 

     //Add the margins as well to the scrollHeight 
     scrollHeight += view.layoutMargins.top 
    } 

    // Adding height for scrollview, according to the sum of all child views 
    self.scrollView.contentSize = CGRect(x: self.scrollView.contentSize.width, y: scrollHeight) 
} 
0

self.scrollview.contentsize.height = containerview.height;