Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell when the background (i.e. not a cell) is touched on a UICollectionView?

I've tried subclassing UICollectionView and overriding touchesBegan:withEvent: and hitTest:WithEvent:, and both of those methods trigger when I touch a cell. However, if I touch the space between the cells, nothing happens at all. Here's what I've created:

@interface WSImageGalleryCollectionView : UICollectionView
@end

..and..

@implementation WSImageGalleryCollectionView

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"Touches began");
    [super touchesBegan:touches withEvent:event];
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    NSLog(@"Hit test reached");
    return [super hitTest:point withEvent:event];
}

@end

Note: gesture recognizers seem to have the exact same issue, which is why I tried going lower-level with touchesBegan.

like image 724
Mason Cloud Avatar asked Nov 03 '13 09:11

Mason Cloud


1 Answers

You just need to set a view as background view that you can then add a gesture recognizer to like:

collectionView.backgroundView = [[UIView alloc] init];
[collectionView.backgroundView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnBackgroundRecognized)]];
like image 63
Michael Loistl Avatar answered Oct 13 '22 19:10

Michael Loistl