在開發(fā)過程中,我們可能會遇到這個問題. 當(dāng)我們給一個view添加了手勢,但是我們又不想點(diǎn)擊view上面的視圖也觸發(fā)手勢.如下圖:
我們在紅色view上添加了手勢,但是又不想點(diǎn)擊黃色view也觸發(fā).其實(shí)這里用到UITapGestureRecognizer的一個代理方法
上代碼,先創(chuàng)建兩個view,并且給bigView添加手勢
self.bigView = [[UIView alloc]initWithFrame:CGRectMake(50, 50, 100, 100)];
self.bigView.backgroundColor = [UIColor redColor];
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bigMap:)];
recognizer.delegate = self;
[self.bigView addGestureRecognizer:recognizer];
[self.view addSubview:self.bigView];
self.smallView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
self.smallView.backgroundColor = [UIColor yellowColor];
[self.bigView addSubview:self.smallView];
實(shí)現(xiàn)UITapGestureRecognizer的一個代理方法,我不用多說,大家一看就明白怎么回事了.這是就解決了防止點(diǎn)擊黃色view也觸發(fā)的問題了
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
if ([touch.view isDescendantOfView:self.smallView]) {
return NO;
}
return YES;
}