Swift 5 CollectionView 长按单元格获取 indexPath

3

我正在寻找一种方法,在单元格上进行长按时获取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
}

长按手势检测
@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)
        }
    }
}

UICollectionViewCell文件中的手势功能会起作用吗? - Mukesh Shakya
2个回答

2

使用gesture.location(in:)获取按下时的坐标。参考:https://developer.apple.com/documentation/uikit/uigesturerecognizer/1624219-location

然后使用indexPathForItem(at:)检索被点击的单元格的IndexPath。参考: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,具体情况可能有所不同!

1
我已经添加了完整的代码(已更新),感谢您,您能否将其添加到您的帖子中以供需要的人使用? - George Heints

0
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并将其删除。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接