Swift 5 CollectionView通过longPress cell获取indexPath

Swift 5 CollectionView get indexPath by longPress cell

当我在单元格上长按时,我正在寻找获取 indexPath 或数据的方法。基本上我可以从 collectionView 中删除相册,为此我需要获取 id.

我的 cellForItem

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AlbumCollectionViewCell", for: indexPath) as! AlbumCollectionViewCell
    cell.data = albumsDataOrigin[indexPath.row]

    let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressGetstureDetected))
    cell.addGestureRecognizer(longPressGesture)

    return cell
}

longPressGetstureDetected

@objc func longPressGetstureDetected(){
    self.delegateAlbumView?.longPressGetstureDetected()
}

删除函数

func longPressGetstureDetected() {
    showAlertWith(question: "You wanna to delete this album?", success: {

        self.deleteAlbum() //Here i need to pass ID
    }, failed: {
        print("Delete cenceled")
    })
}

对于寻找完整答案的人

@objc func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {

    if longPressGestureRecognizer.state == UIGestureRecognizer.State.began {
        let touchPoint = longPressGestureRecognizer.location(in: collectionView)
        if let index = collectionView.indexPathForItem(at: touchPoint) {
            self.delegateAlbumView?.longPressGetstureDetected(id: albumsDataOrigin[index.row].id ?? 0)
        }
    }
}

首先使用 gesture.location(in:) 参考:https://developer.apple.com/documentation/uikit/uigesturerecognizer/1624219-location

获取压力机的坐标

然后使用indexPathForItem(at:) 检索触摸的单元格的索引路径。参考:https://developer.apple.com/documentation/uikit/uicollectionview/1618030-indexpathforitem

基于此,您可能不需要为每个单元格使用不同的手势识别器,您可以将其注册到集合视图一次。


George Heints 根据上述提供的解决方案:

@objc func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {

    if longPressGestureRecognizer.state == UIGestureRecognizer.State.began {
        let touchPoint = longPressGestureRecognizer.location(in: collectionView)
        if let index = collectionView.indexPathForItem(at: touchPoint) {
            self.delegateAlbumView?.longPressGetstureDetected(id: albumsDataOrigin[index.row].id ?? 0)
        }
    }
}

我建议使用 State.recognized 而不是 State.began,你的里程可能会有所不同!

import UIKit

extension UIResponder {

    func next<T: UIResponder>(_ type: T.Type) -> T? {
        return next as? T ?? next?.next(type)
    }
}

extension UICollectionViewCell {

    var collectionView: UICollectionView? {
        return next(UICollectionView.self)
    }

    var indexPath: IndexPath? {
        return collectionView?.indexPath(for: self)
    }
}

借助此扩展,您可以从集合视图单元格文件中了解集合视图的索引路径。你可以简单地从数据数组中通过indexPath找到照片的id并删除它。