【问题标题】:Change content size UIScrollView dynamically动态更改内容大小 UIScrollView
【发布时间】:2021-10-23 02:45:00
【问题描述】:

我有一个滚动视图,当第一次加载视图时,大小是动态设置的,但是当我点击按钮时,我的元素的内部大小发生了变化,我需要改变滚动的内部大小,但是它没有改变。有人知道怎么解决吗?

       DispatchQueue.main.async {
        var contentRect = CGRect()
        for view in self.scrollView.subviews {
            contentRect = contentRect.union(view.frame)
            self.scrollView.contentSize = contentRect.size
        }
}

【问题讨论】:

  • 结束后可以设置contentSize,无需为每一项调用。点击按钮时如何调用这段代码?
  • 在为滚动视图设置约束时,我只调用一次。
  • @alexananchenko - 如果您的约束设置正确,它是自动的...无需计算和明确设置.contentSize

标签: swift uiscrollview intrinsic-content-size


【解决方案1】:

如果您真的不想使用自动布局/约束,您可以在每次从滚动视图中添加(或删除)子视图时调用此函数,或者在更改子视图:

func updateContentSize() -> Void {
    // this will get the right-edge of the right-most subview
    let width = scrollView.subviews.map {$0.frame.maxX}.max() ?? 0.0

    // this will get the bottom-edge of the bottom-most subview
    let height = scrollView.subviews.map {$0.frame.maxY}.max() ?? 0.0

    // set the contentSize
    scrollView.contentSize = CGSize(width: width, height: height)
}

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 2011-07-24
    • 1970-01-01
    • 2012-09-27
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多