首页 > 解决方案 > 如何让scrollview在swift中分别滚动到它的内容高度

问题描述

我在情节提要中有如下视图层次结构

在此处输入图像描述

这里是内容的主要限制top = 0, leading = 0, trailing = 0, bottom = 0

这里是滚动视图约束top = 0, leading = 0, trailing = 0, bottom = 0

在这里查看约束top = 0, leading = 0, trailing = 0, bottom = 0

对于ContentView约束top = 0, leading = 0, trailing = 0

对于TblReview约束top = 0, leading = 0, trailing = 0, bottom = 20

对于Productcollectionview约束top = 0, leading = 0, trailing = 0, bottom = 20, height = 400

我在 swift 文件中有 Productcollectionview 高度出口,如下所示

而且我不希望collectionview单独滚动..我希望总视图根据collectionview单元格滚动..所以我写了下面的代码但是使用这段代码contentView and tblReview also scrolling upto productioncollectionview height我需要contentView应该滚动到它的内容高度并且tblReview应该滚动到它的行

如何分别滚动到它的高度。

请帮我解决这个问题

  @IBOutlet weak var productCollHeight: NSLayoutConstraint!

 override func viewDidLoad() {
    super.viewDidLoad()
    
    productCollectionView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
} 
 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    let collectionView = object as? UICollectionView
    if collectionView == self.productCollectionView{
        if(keyPath == "contentSize"){
            if let newvalue = change?[.newKey]
            {
                let newsize  = newvalue as! CGSize
                self.productCollHeight.constant = newsize.height
            }
        }
    }
    }

@IBAction func aboutCompany(_ sender: UIButton){
self.productCollectionView.isHidden = true
self.tblReview.isHidden = true
self.contentView.isHidden = false
}

@IBAction func review(_ sender: UIButton){

self.productCollectionView.isHidden = true
self.tblReview.isHidden = false
self.contentView.isHidden = true
}

@IBAction func productOfSeller(_ sender: UIButton){
self.productCollectionView.isHidden = false
self.tblReview.isHidden = true
self.contentView.isHidden = true

}

我根据需要隐藏和显示 tblReview 和 contentView

使用上面的代码 tblReview 和 contentView 也滚动到 productCollectionView 高度..请帮我解决这个错误

编辑:没有滚动share this seller视图,所以这里的contentView 高度不是那么长,但是如果我滚动 contentView 也滚动太长,就像 productioncollectionview

这是 contentView,它像 productioncollectionview 一样滚动太久 在此处输入图像描述

标签: swiftuiscrollviewheight

解决方案


如果您的所有约束都是正确的,而不仅仅是像这样使用它,您就不需要每次都计算。UICollectionViewintrinsicContentSize它会正确计算它。

final class ContentSizedCollectionView: UICollectionView {
    override var contentSize:CGSize {
        didSet {
            invalidateIntrinsicContentSize()
        }
    }

    override var intrinsicContentSize: CGSize {
        layoutIfNeeded()
        return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
    }
}

将该代码放在控制器中或您想要放置的任何位置并将ContentSizedCollectionView类分配给您的collectionview。

注意:您也可以UITableView在创建 for 之后使用它UITableView


推荐阅读