【问题标题】:Define correctly height for UIScrollView为 UIScrollView 定义正确的高度
【发布时间】:2017-12-11 16:13:57
【问题描述】:

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

  • UIScrollView
    • UIView // 容器 view
    • UIImageView // Constraint 顶边 = 20 相对于 UIView
    • UITextView // Constraint 顶边 = 40 相对于 UIImageView
    • UITextView // Constraint 顶边 = 20 相对于 UITextView
    • UIButton // Constraint 顶边 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 的正确高度,根据他们的内容进行调整。

【问题讨论】:

  • 如果你在滚动视图底部的最后一个按钮上添加一个约束,你应该手动设置内容的大小。
  • @agibson007 但我没有添加这个约束,只在上面的uiview底部添加约束
  • 是的,这就是我的意思,对不起。那应该行得通。请参阅我不久前给出的这个答案。 stackoverflow.com/questions/42684594/…

标签: ios swift autolayout storyboard


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多