如果一個UIView關聯多個UIGestureRecognizer, 會發生一個奇怪的問題,如下面代碼
[cpp]
UIPanGestureRecognizer *pang = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panned:)];
[self.view addGestureRecognizer:pang];
UISwipeGestureRecognizer *swip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swip:)];
[self.view addGestureRecognizer:swip];
- (void)swip:(UISwipeGestureRecognizer *)gesture {
NSLog(@"swip");
}
- (void)panned:(UIPanGestureRecognizer *)gesture {
NSLog(@"pan");
}
UIPanGestureRecognizer *pang = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panned:)];
[self.view addGestureRecognizer:pang];
UISwipeGestureRecognizer *swip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swip:)];
[self.view addGestureRecognizer:swip];
- (void)swip:(UISwipeGestureRecognizer *)gesture {
NSLog(@"swip");
}
- (void)panned:(UIPanGestureRecognizer *)gesture {
NSLog(@"pan");
}
結果是看不到swip的手勢觸發。
原因是系統event傳遞是,當有一個相響了,event就不會傳遞下去了。
要想兩個gesturerecognizer都起作用,只需要加幾行代碼就可以了
[cpp]
swip.delegate = self;
swip.delegate = self;
然後實現,返回YES,表示還要響應otherGestureRecognizer.
[cpp]
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
這下就可以看到swip在consol中打印出來。