我已经尝试了子类化UICollectionView并覆盖touchesBegan:withEvent:和hitTest:WithEvent:,当我触摸单元格时,这两个方法都会触发.但是,如果我触摸单元格之间的空间,则根本不会发生任何事情.这是我创造的:
@interface WSImageGalleryCollectionView : UICollectionView @end
..和..
@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
注意:手势识别器似乎有完全相同的问题,这就是为什么我尝试使用touchesBegan进行更低级别的操作.
解决方法
您只需将视图设置为背景视图,然后就可以添加手势识别器:
collectionView.backgroundView = [[UIView alloc] init]; [collectionView.backgroundView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnBackgroundRecognized)]];