Swift: UICollectionView selecting cell indexPath issues

前端 未结 2 1655
-上瘾入骨i
-上瘾入骨i 2021-02-03 11:46

I am trying to do a Collection View whereby someone selects a cell and for each selection it takes them to another View Controller that ho

2条回答
  •  半阙折子戏
    2021-02-03 12:17

    (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.

提交回复
热议问题