ios - 为 UIScrollView 正确定义高度

标签 ios swift autolayout storyboard

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

相关文章:

ios - 仅在下方的一个 View 上绘制阴影

ios - iOS 9 的新字体将应用于 Ionic 应用程序?

ios自动布局标签定位

ios - AutoLayout 未将 subview 固定到 super View

iphone - 如何在ViewController中初始化实例变量和属性

ios - 存储用户信用信息

ios - 无法将 PNG 图像加载为 UIImage

swift - 内存泄漏与方法 NSRegularExpression.matchesInString()

ios - 升级到最新的 XCode beta 3 后 Swift 应用程序崩溃

ios - UILabel 大小更改不会通过自动布局进行动画处理