我正在使用 Swift3
创建一个应用程序,我很难为 UIScrollView
正确定义高度,我正在使用 autolayout
和创建这个结构:
UIScrollView
UIView
//容器view
UIImageView
//Constraint
Top Edges = 20 相对于UIView
UITextView
//Constraint
Top Edges = 40 相对于UIImageView
UITextView
//Constraint
Top Edges = 20 相对于UITextView
UIButton
//Constraint
Top Edges 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
,根据内容调整。
最佳答案
关闭!让我们为每个 View 添加上边距:
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)
}
关于ios - 为 UIScrollView 正确定义高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44969496/