为 UIScrollView 正确定义高度



>我正在使用Swift3创建一个应用程序,并且很难正确定义UIScrollView的高度,我正在使用autolayout并创建此结构:

  • UIScrollView
    • UIView//容器view
    • UIImageView//Constraint顶边 = 20 相对于UIView
    • UITextView//Constraint顶边 = 40 相对于UIImageView
    • UITextView//Constraint顶边 = 20 相对于UITextView
    • UIButton//Constraint相对于UITextView的顶部边缘 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"边距",我想知道任何方法来计算UIScrollView的正确高度,并根据它们的内容进行调整。

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

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)
}

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

最新更新