为UIScrollView正确定义高度

时间:2017-07-07 11:20:19

标签: ios swift autolayout storyboard

我正在使用Swift3创建应用,并且我很难为UIScrollView正确定义高度,我使用autolayout并创建此结构:< / p>

  • UIScrollView
    • UIView //容器view
    • UIImageView // Constraint热门边缘= 20与UIView相关
    • UITextView // Constraint热门边缘= 40与UIImageView相关
    • UITextView // Constraint热门边缘= 20与UITextView相关
    • UIButton // ConstraintUITextView相关的热门边缘30

目前,我正在使用此逻辑来计算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&#34;边距&#34;,我想知道任何方法来计算{{1}的正确高度根据其内容进行调整。

2 个答案:

答案 0 :(得分: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)
}

答案 1 :(得分:0)

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