在開發過程中,我們可能會遇到這個問題. 當我們給一個view
添加了手勢,但是我們又不想點擊view
上面的視圖也觸發手勢.如下圖:
我們在紅色view
上添加了手勢,但是又不想點擊黃色view
也觸發.其實這裡用到UITapGestureRecognizer
的一個代理方法
上代碼,先創建兩個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];
實現UITapGestureRecognizer
的一個代理方法,我不用多說,大家一看就明白怎麼回事了.這是就解決了防止點擊黃色view
也觸發的問題了
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{ if ([touch.view isDescendantOfView:self.smallView]) { return NO; } return YES; }
是不是很簡單啊.最後送大家一個我自己用無人機拍攝的小視頻.