Quiet Islet
Quiet Islet

Reputation: 536

didSelect does not work in UICollectionviewCell to select UICollectionViewController

I wrote didSelectItemAtIndexPath func in UICollectionViewCell to select a UICollectionViewController. I wrote the code in two ways but it doesnot work at all. Also, I don't getting an error in there.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    if indexPath.item == 0 {

        let layout = UICollectionViewFlowLayout()
        let controller1 = DigitalSLRCon(collectionViewLayout: layout)
        let nav = UINavigationController()
        nav.pushViewController(controller1, animated: true)

// OR

        let layout = UICollectionViewFlowLayout()
        let controller1 = DigitalSLRCon(collectionViewLayout: layout)
        navigationController?.pushViewController(controller1, animated: true)

    }

Upvotes: 0

Views: 474

Answers (2)

zombie
zombie

Reputation: 5259

Please remove the delegates from the UICollectionViewCell The delegates are not for the cell but the UICollectionView handler

If you want to change some element in the cell

you can override the default variables in the cell like this

override var isSelected: Bool {
   didSet {
      if isSelected {
         //do something
      } else {
         //not selected
      }
   }
}

override var isHighlighted: Bool {
   didSet {
      if isHighlighted {
         //do something
      } else {
         //not selected
      }
   }
}

Upvotes: 0

mag_zbc
mag_zbc

Reputation: 6982

didSelectItemAtIndexpathis a function of UICollectionViewDelegate - you don't implement it in the cell, but in your CollectionView's delegate, so probably the view controller which contains the collection view.

  1. Make the UIViewController that holds the collection view conform to UICollectionViewDelegate protocol
  2. Assign that view controller to collection view's delegate property
  3. Implement the didSelectItemAtIndexpath function in the view controller

Upvotes: 1

Related Questions