>我正在使用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;