有一个场景:
点击某个按钮,present一个控制器,该控制器有一个透明背景色,然后上面有一个view展现(为方面叙述,称为bgView),点击控制器的view可以使控制器消失,而点击bgView控制器不消失。
这种简单的可以添加两个手势:
在控制器的view上添加手势,点击可以使得控制器消失;
在bgView上添加手势,点击也触发action,但是里面什么都不做。
类似于:
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissBgView)];
[self.view addGestureRecognizer:tapGesture];
UITapGestureRecognizer *bgViewTapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doNothing)];
[bgView addGestureRecognizer:bgViewTapGesture];
- (void)dismissBgView
{
[UIView animateWithDuration:0.5 animations:^{
self.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.1];
self.bgView.top = HEIGHT_SCREEN * 1.25;
} completion:^(BOOL finished) {
[self dismissViewControllerAnimated:NO completion:nil];
}];
}
//什么也不做
- (void)doNothing
{
}
该方法可以解决:
- 点击控制器view弹窗消失
- 点击bgView控制器不消失
但,这种有个问题:如果我在bgView上添加了collectionView或者tableView,此时会发现,点击collectionView或者tableView里面的selected代理方法,没反应
原因也很简单,点击bgView的时候,tap方法直接拦截了,跳到了doNothing里面。那么,这时该怎么做呢?
网上查一下,没找到什么有用的资料,估计是太简单了吧
我的做法是:
controller的view添加touchesBegan方法,在touchesBegan里面实现控制消失的操作dismissBgView
bgView继承一个view(比如:NoTouchBaseView),该view里面只有一个方法,就是touchesBegan,而里面什么都没有。
@interface NoTouchBaseView : UIView
@end
#import "NoTouchBaseView.h"
@implementation NoTouchBaseView
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
}
@end
如此,则可以实现:
- 点击controlller的view控制器消失
- 点击bgView控制器不消失
- 点击collectionView可以正常接收事件