简体   繁体   English

动态更改内容大小 UIScrollView

[英]Change content size UIScrollView dynamically

I have a scroll view, when the view is first loaded, the size is set dynamically, but when I click on the button, the internal size of my elements changes and I need to change the internal size of the scroll, but it does not change.我有一个滚动视图,当视图第一次加载时,大小是动态设置的,但是当我点击按钮时,我的元素的内部大小发生了变化,我需要改变滚动的内部大小,但它不会改变。 Someone knows how to fix it?有人知道如何解决吗?

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

If you really don't want to use auto-layout / constraints, you can call this function each time you add (or remove) a subview from the scroll view, or after you've changed the size(s) of the subview(s):如果你真的不想使用自动布局/约束,你可以在每次从滚动视图中添加(或删除)子视图时调用此函数,或者在更改子视图的大小后调用此函数(秒):

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

This solution is for auto-layout/constraints.此解决方案适用于自动布局/约束。 You need a reference constraint to manipulate the height of the inner container view of the scrollview.您需要一个引用约束来操纵滚动视图的内部容器视图的高度。

private var _constraintInnerContainerScroll:NSLayoutConstraint?

You need to set the initial height of the inner container view, suppose 700.0需要设置内部容器view的初始高度,假设700.0

private let _containerViewHeightFixed    : CGFloat = 700.0

then you need to save the reference那么你需要保存参考

_constraintInnerContainerScroll = _containerView.heightAnchor.constraint(equalToConstant: _containerViewHeightFixed)
_constraintInnerContainerScroll?.isActive = true

You initial view is setup and ready, now suppose you add 2 more subview of height 100.0 each, now your new inner container view height should be 700.0+200.0 = 900.0您的初始视图已设置并准备就绪,现在假设您再添加 2 个高度为 100.0 的子视图,现在您的新内部容器视图高度应为 700.0+200.0 = 900.0

    if let const1 = _constraintInnerContainerScroll{
            const1.constant = _containerViewHeightFixed + 200.0
            UIView.animate(withDuration: 0.5) {            
           self?._containerView.layoutIfNeeded()
    }else{
           print("constraint reference not saved")
    }

let me know if this works for you, or if this can be improved.让我知道这是否适合您,或者是否可以改进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM