簡體   English   中英

檢測位於另一個 uicollectionview 內部的 uicollectionView 的哪個 UICollectionViewCell 在中心

[英]Detect which UICollectionViewCell of a uicollectionView that is inside another uicollectionview is in the center

So i have a horizontal UICollectionView of images that is inside a vertical UICollectionView and i want to detect which cell is in the center on the horizonal UICollectionView when i select a cell from the vertical one I tried to send a notification and call a function that does這項工作,但由於它重復使用同一個單元格,所以它被多次調用,所以最后我沒有得到適當的 indexPath。

而且當我點擊圖像時,水平collectionView的“didSelectItemAt”被調用,有沒有辦法讓垂直collectionView被調用? 謝謝

你最好的選擇是通過協議代表

為您的集合視圖單元創建協議

protocol yourDelegate: class {
    
    func didSelectCell(WithIndecPath indexPath: IndexPath, InCollectionView collectionView: UICollectionView) -> Void
    
}

在您的單元格中,創建一個名為 setup 的 function,您可以在 cellForRow 中調用它。 在您的單元格中,為自己創建一個觸摸識別器。 禁用集合視圖的單元格選擇,因為當用戶觸摸給定單元格時將調用這些委托。

class yourCell: UICollectionViewCell  {
    
    var indexPath: IndexPath? = nil
    var collectionView: UICollectionView? = nil
    
    weak var delegate: yourDelegate? = nil
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        let selfTGR = UITapGestureRecognizer(target: self, action: #selector(self.didTouchSelf))
        self.contentView.addGestureRecognizer(selfTGR)
    }
    
    @objc func didTouchSelf() {
        guard let collectionView = self.collectionView, let indexPath = self.indexPath else {
            return
        }
        
        delegate?.didSelectCell(WithIndecPath: indexPath, InCollectionView: collectionView)
    }
    
    func setupCell(WithIndexPath indexPath: IndexPath, CollectionView collectionView: UICollectionView, Delegate delegate: yourDelegate) {
        self.indexPath = indexPath
        self.collectionView = collectionView
        self.delegate = delegate
    }
    
}

在您的 viewController 中,為此協議創建擴展,如果您做的一切正確,當用戶觸摸您的單元格時,單元格將通過此委托呼叫您。

extension YourViewController: yourDelegate {
    
    func didSelectCell(WithIndecPath indexPath: IndexPath, InCollectionView collectionView: UICollectionView) {
        //You have your index path and you can "if" your colllection view
        
        if collectionView == self.yourFirstCollectionView {
            
        } else if collectionView == self.yourSecondCollectionView {
            
        }
        //and so on..
    }
    
}

由於協議是“:類”,我們可以為您的委托屬性使用弱,因此不會發生 memory 泄漏。 我在我的項目中對 tableViews 和 collectionViews 使用這種方法。

暫無
暫無

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

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