Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Buttons in a UICollectionView don't receive touch events

I've been looking around for a while now but can't seem to work out how to stop the collection view cells from consuming the touch events.

I need the touch events to be passed down into the respective cells so that the buttons within the cells can be pressed. I was thinking i might need to work out how to disable the UICollectionView's didSelectCellAtIndexFunction?

I've also seen this as a potential solution: collectionView.cancelsTouchesInView = false

Also this link might help someone answer my question: How to add tap gesture to UICollectionView , while maintaining cell selection?

Thanks in advance!

Edit:

Also I should add: my buttons are added to a view that is in turn added to the cell's contentView. My code is done all programatically and so I am not using interface Builder at all.

like image 255
Callum C Avatar asked Nov 02 '25 00:11

Callum C


1 Answers

func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        return false // all cell items you do not want to be selectable
    }

Assuming all buttons are connected to the same selector, you need a way to differentiate which cell's button has been clicked. One of the ways for finding out the button's cell's index is:

func buttonPressed(button: UIButton) {
    let touchPoint = collectionView.convertPoint(.zero, fromView: button)
    if let indexPath = collectionView.indexPathForItemAtPoint(touchPoint) {
        // now you know indexPath. You can get data or cell from here.
    }
}
like image 66
Joe Avatar answered Nov 03 '25 15:11

Joe