I have a UICollectionView
that has different items in it. When I tap on an item, I use:
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
to figure out what was touched and then basically set the alpha of that view to 0 to hide it. That all works fine. Now what I would like to do is when you tap on the white space surrounding all of the UICollectionViewCell
s all of the views then appear again. I am having trouble finding a method that will allow me to know when the white space around the cells has been touched. Is there a good way to do that? I have tried setting up a gesture recognizer, but when I do that, my method
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
isn't called. Is there some way to to just implement the gesture recognizer and from there determine if a cell was tapped and if so hide that cell, else show all the hidden cells? Thanks.
some "cosmetics" for Swift 4.2: (thxs to other authors above.. :) )
I've managed to fix this problem by using a
UITapGestureRecognizer
on theUICollectionView
backgroundView
. It's in Swift, but the idea is clear:And the callback:
This worked for me on Swift 2.3
Step 1 : Implement the UIGestureRecognizerDelegate protocol
Step 2 : Set UITapGestureRecognizer on the UICollectionView backgroundView
Step 3 : Handle what to do on tap inside handleTap function
didSelectItem delegate method will be called only when the user selects collectionViewCell. The space between the cells may vary depending on the each cell Size, you can specify only min spacing. To recieve the touches keep supplementaryView as backgroundView by changing its zindex, add touch detection to it. Hope this will help you. :)
Based on Paul Popiel's answer but in Objective C
To set up the gesture recognizer:
And to handle the tap and recognize if it is touching a cell or space not covered by a cell
I ran into a similar scenario in my project and solved it by doing the following:
Implement the
UIGestureRecognizerDelegate
protocolThen implement the following function in the protocol:
Basically if the click is on a cell then your gesture recognizer doesn't begin, allowing the normal selection/deselect delegates to run. Otherwise if it's on empty space your recogniser handles the tap and runs its handler.