子視圖并不響應(yīng) tap 點(diǎn)擊觸摸手勢(shì) , 而是至于父視圖響應(yīng) tap 觸摸手勢(shì)的效果 , 精確定位觸摸的位置:
1.從代理方法能否開(kāi)始過(guò)濾手勢(shì)觸摸的位置:
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer;
2.從手勢(shì)能否進(jìn)入 Possible 狀態(tài)就開(kāi)始過(guò)濾手勢(shì)觸摸的位置:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch;
//
// GestureConditionViewController.m
// 15-手勢(shì)實(shí)踐
//
// Created by miaodong on 2017/6/19.
// Copyright ? 2017年 miaodong. All rights reserved.
//
#import "GestureConditionViewController.h"
@interface GestureConditionViewController () <UIGestureRecognizerDelegate> {
UIView *_superView;
UIView *_subView;
UITapGestureRecognizer *_tap;
}
@end
@implementation GestureConditionViewController
#pragma mark - life Cycle
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.edgesForExtendedLayout = UIRectEdgeNone;
_superView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 200, 200)];
_superView.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:_superView];
_subView = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 100, 100)];
_subView.backgroundColor = [UIColor orangeColor];
[_superView addSubview:_subView];
_tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
_tap.delegate = self;
[_superView addGestureRecognizer:_tap];
}
#pragma mark - 手勢(shì)方法
- (void)tap:(UITapGestureRecognizer *)tapGesture {
[self alertMessage:@"tap"];
}
- (void)alertMessage:(NSString *)message {
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"AlertVC" message:message preferredStyle:UIAlertControllerStyleAlert];
[alertVC addAction:[UIAlertAction actionWithTitle:@"確定" style: UIAlertActionStyleCancel handler:nil]];
[self presentViewController:alertVC animated:YES completion:nil];
}
//方法一:
#pragma mark - <UIGestureRecognizerDelegate>
//讓父視圖響應(yīng)這個(gè) tap 手勢(shì),子視圖不響應(yīng)這個(gè)手勢(shì):
//- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
// if (gestureRecognizer == _tap) {
// CGPoint location = [gestureRecognizer locationInView:_superView];
// //如果在第一個(gè)參數(shù)方塊里包含了第二個(gè)參數(shù)的點(diǎn)坐標(biāo):
// if (CGRectContainsPoint(_subView.frame, location)) {
// return NO;
// }
// return YES;
// }
// return YES;
//}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if (gestureRecognizer == _tap) {
//如果觸摸位置所在的視圖不是父視圖 , 并且 觸摸位置所在的視圖是父視圖的子孫視圖:
// if (touch.view != _superView && [touch.view isDescendantOfView:_superView]) {
// //那么就不響應(yīng)手勢(shì):
// return NO;
// }
//用下面這種判斷也是可以的~因?yàn)樽右晥D是添加到父視圖上的,觸摸點(diǎn)擊子視圖位置的時(shí)候是 摸不到 父視圖上的點(diǎn)的!
if (!(touch.view == _superView)) {
return NO;
}
return YES;
}
return YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end