3

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.

Callum C
  • 33
  • 7

2 Answers2

1
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.
    }
}
Joe
  • 2,386
  • 1
  • 22
  • 33
  • Thanks Joseph but I'm not using NIB's, my collectionView, cells, and buttons are made all programatically and my views are definitely added to the contentView – Callum C May 31 '17 at 11:57
  • then try overriding the UICollectionViewDelegate's collectionView(_:shouldSelectItemAt:) method and return false on items where you do not want the collectionView(_:didSelectItemAt:) to be called. – Joe May 31 '17 at 11:59
1

Try on your cell.

self.contentView.isUserInteractionEnabled = false