检测位于另一个 uicollectionview 内的 uicollectionView 的哪个 UICollectionViewCell 位于中心

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

所以我有一个水平的 UICollectionView 图像,它位于一个垂直的 UICollectionView 中,我想检测哪个单元格位于水平 UICollectionView 的中心,当我 select 一个来自垂直单元格的单元格时 我试图发送一个通知并调用一个函数来完成这项工作,但它被多次调用,因为它重复使用了同一个单元格,所以最后我没有得到适当的 indexPath。

而且当我点击图像时,水平 collectionView 的“didSelectItemAt”被调用,有没有办法让垂直的被调用? 谢谢

最好的选择是通过协议进行代表

为您的集合视图单元格创建协议

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

在您的单元格中,创建一个名为 setup 的函数,您可以在 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..
    }
    
}

由于协议是“:class”,我们可以为您的委托使用 weak 属性,这样就不会发生内存泄漏。我在整个项目中对 tableView 和 collectionView 使用这种方法。