I am working on a grid based game (like minesweeper). It is a 2d grid that I am displaying using a UICollectionView that contains a set of custom UICollectionViewCell cells.
I want to be able to listen to touch events on individual cells. Is it fine to add an UITapGestureRecognizer() to each of the cells (on a 20x20 board, for example). Or is there a better way?
I understand from Ahmad's reply that using this works for single taps:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(indexPath.row)
}
However, I want different event handlers for single vs double taps on the cells.
If you want to let the base container as a UICollectionView (which I find it a good idea), I doubt that you need to add UITapGestureRecognizer to it, all you have to do is to let your class (Controller) to conforms to UICollectionViewDelegate its Delegate and implement collectionView:didSelectItemAtIndexPath:.
Also, the benefit that you'll get when implementing this method is you can easily determine which cell has been selected, by checking what is the indexPath.row
of the selected cell, as follows:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(indexPath.row)
}
Don't forget to:
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { //...
EDIT:
In case of you want to add a double tap functionality to your collection view, I suggest to check this answer to achieve it.
Hope this helped.