Swift 5 CollectionView 通过 longPress cell 获取 indexPath



当我在单元格上长按时,我正在寻找获取索引路径或数据的方法。基本上我可以从收藏视图中删除相册,为此我需要获取id

我的单元格项目列表

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
}

longPressGetstureDetect

@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.recognize而不是State.开始,您的里程可能会有所不同!

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 。您只需通过数据数组中的indexPath找到照片的id并将其删除即可。

最新更新