Swift: UICollectionView selecting cell indexPath issues

放肆的年华 提交于 2019-12-02 21:02:55

(NOTE: I updated this for Swift 4 and more modern practices.)

I stick to UIView objects as much as possible.

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    guard let cell = collectionView.cellForItem(at: indexPath) else { return }

    performSegue(withIdentifier: "showDetail", sender: cell)
}

Then in prepare(for:sender:)

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    switch segue.identifier {
    case "showDetail":
        guard let indexPath = (sender as? UIView)?.findCollectionViewIndexPath() else { return }
        guard let detailViewController = segue.destination as? DetailViewController else { return }

        detailViewController.selectedImageName = cellImages[indexPath.row]
        detailViewController.selectedLabel = cellLabels[indexPath.row]

    default: return
    }
}

I used an extension I created a while ago findCollectionViewIndexPath()

extension UIView {

    func findCollectionView() -> UICollectionView? {
        if let collectionView = self as? UICollectionView {
            return collectionView
        } else {
            return superview?.findCollectionView()
        }
    }

    func findCollectionViewCell() -> UICollectionViewCell? {
        if let cell = self as? UICollectionViewCell {
            return cell
        } else {
            return superview?.findCollectionViewCell()
        }
    }

    func findCollectionViewIndexPath() -> IndexPath? {
        guard let cell = findCollectionViewCell(), let collectionView = cell.findCollectionView() else { return nil }

        return collectionView.indexPath(for: cell)
    }

}

I have a suspicion that you have a segue in the storyboard already and don't need func collectionView(, didSelectItemAtIndexPath:), but either way, the prepare segue should work.

Swift 3.0

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let iPath = self.collectionView.indexPathsForSelectedItems
    let indexPath : NSIndexPath = iPath![0] as NSIndexPath
    let rowIndex = indexPath.row
    print("row index = \(rowIndex)")
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!