Swift 5 CollectionView通过longPress单元格获取indexPath

时间:2019-06-05 11:06:13

标签: swift uicollectionview long-press

当我在单元格上执行longPress时,我正在寻找获取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)
        }
    }
}

2 个答案:

答案 0 :(得分:1)

首先使用{{variableName}}['key']参考:https://developer.apple.com/documentation/uikit/uigesturerecognizer/1624219-location

获取印刷机的坐标

然后使用gesture.location(in:)检索所触摸的单元格的IndexPath。参考:https://developer.apple.com/documentation/uikit/uicollectionview/1618030-indexpathforitem

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


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

indexPathForItem(at:)

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

答案 1 :(得分: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并将其删除。