UITapGestureRecognize 和UITouch 事件響應衝突解決
阿新 • • 發佈:2019-02-17
做一個ViewController是A,裡面有一個圓形控制按鈕B,在B的裡面有一個操作控制按鈕C
在原來的AViewController裡面有一個UITapGestureRecognizer事件,點選會使得B消失。
UITapGestureRecognizer *tapAction = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
[self addGestureRecognizer:tapAction];
在檢視C中,使用了UITouch相關方法
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event; - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event; - (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
遇到問題是,在C檢視中,如果做點選操作,這時候會被A檢視認為是UITapGestureRecognizer事件,這樣會使得B檢視和C檢視消失
解決的辦法是:
首先是A檢視,使用UIGestureRecognizerDelegate
UITapGestureRecognizer *tapAction = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)]; tapAction.delegate = self; [self addGestureRecognizer:tapAction];
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if ([touch.view isKindOfClass:[AViewController class]]) {
return YES;
}
return NO;
}
如此既可以解決,兩邊的事件不會互相影響。