有时候需要处理点击UICollectionView空白区域的事件,如果我们直接添加一个单击手势,就会发现,当点击UICollectionViewCell时,也是执行的单击手势的方法,而不是执行didSelectItemAtIndexPath;这时候可以通过手势代理方法解决,区分点击的是UICollectionView空白处,还是UICollectionViewCell。如下:
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)]; [_collectionView addGestureRecognizer:tap]; tap.delegate = self;
同时遵循手势代理:UIGestureRecognizerDelegate
实现代理方法:
@interface BGBroadcastFriendView ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout,UITextFieldDelegate,UIGestureRecognizerDelegate> - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch { //如果点击的是collectionView空白处,那么响应手势,接下去执行单击手势的方法即可 if ([touch.view isKindOfClass:[UICollectionView class]]) { return YES; } //如果点击的是UICollectionViewCell,那么touch.view=UICollectionView,取消手势响应 return NO; }
单击手势:
- (void)tap:(UITapGestureRecognizer *)gesture { [self endEditing:YES]; }