Why UICollectionView didSelect method does not work?

15,223

Solution 1

i Know this may be late, but for the sakes of feature purpose, CollectionView[didSelectItem] not responding to touch could be as a result of you also enalbing addGestureRecognizer so check if you have set a gesture recognizer on your CollectionView like so collectionView?.addGestureRecognizer(tapGestRecognizer)

Solution 2

I just encountered this case.

Did you put a button or an interactive view in a collection view cell? Your touch is handled by it, then didSelect isn't called.

Turn off User Interaction Enabled property by Interface builder, or set false programmatically.

enter image description here

Solution 3

Be sure that you don't have UICollectionViewDelegate and UICollectionViewDelegateFlowLayout together.

Solution 4

check in UiCollectionviewCell subclass isUserInteractionEnabled property or set it programaticaly to true

self.contentView.isUserInteractionEnabled = true
Share:
15,223
Doe
Author by

Doe

Updated on June 09, 2022

Comments

  • Doe
    Doe about 2 years

    I've created my UICollectionView programmatically and in this case my didSelectItemAtIndexPath method does not call at all.

    let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: CGRectGetWidth(self.view.frame), height: 360), collectionViewLayout: layout)
    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.userInteractionEnabled = true
    

    So, what is a problem? Why when I tap on the cells I do not get my response?

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print("Selected Cell: \(indexPath.row)")
    }
    
  • Lax
    Lax about 4 years
    Thank you. This saved my time. I enabled gesture recognizer on my table view whose cells contained collectionView and it prevented the delegates from being triggering
  • Omid Golparvar
    Omid Golparvar over 3 years
    Thanks. In my case, mistake was I added gesture recognizer on view controller.
  • User1075
    User1075 over 3 years
    You Made My Day Thanks
  • internetdotcom
    internetdotcom about 2 years
    What do you do if you need UICollectionViewDelegateFlowLayout ? What about the flow layout breaks tapping cells?
  • Massimo Pavanel
    Massimo Pavanel about 2 years
    I think that you have misunderstood the flowLayout. Basically Flowlayout gives you the feature to react on the dimension of the collection view frame and made calculation to bring them to the cell Try this: func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let spazio = 10 let width = (yourCollection.frame.size.width/2)-(spazio * 2) let height = (width * 1.5) + (spazio * 2) return CGSize(width: cellWidth, height: cellHeight) } Never seen flownlayout break anything