簡體   English   中英

動態更改內容大小 UIScrollView

[英]Change content size UIScrollView dynamically

我有一個滾動視圖,當視圖第一次加載時,大小是動態設置的,但是當我點擊按鈕時,我的元素的內部大小發生了變化,我需要改變滾動的內部大小,但它不會改變。 有人知道如何解決嗎?

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

如果你真的不想使用自動布局/約束,你可以在每次從滾動視圖中添加(或刪除)子視圖時調用此函數,或者在更改子視圖的大小后調用此函數(秒):

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

此解決方案適用於自動布局/約束。 您需要一個引用約束來操縱滾動視圖的內部容器視圖的高度。

private var _constraintInnerContainerScroll:NSLayoutConstraint?

需要設置內部容器view的初始高度,假設700.0

private let _containerViewHeightFixed    : CGFloat = 700.0

那么你需要保存參考

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

您的初始視圖已設置並准備就緒,現在假設您再添加 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")
    }

讓我知道這是否適合您,或者是否可以改進。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM