手势的3个混淆属性
/**
* 本节介绍tap的3个弄不太林清并且容易混淆的属性:
cancelsTouchesInView/delaysTouchesBegan/delaysTouchesEnded
* (0)首先要知道的是
1.这3个属性是作用于GestureRecognizers(手势识别)与触摸事件之间联系的属性。实际应用中好像很少会把它们放到一起,大多都只是运用手势识别,所以这3个属性应该很少会用到。
2.对于触摸事件,window只会有一个控件来接收touch。这个控件是首先接触到touch的并且重写了触摸事件方法(一个即可)的控件
3.手势识别和触摸事件是两个独立的事,只是可以通过这3个属性互相影响,不要混淆。
* (1)在默认情况下(即这3个属性都处于默认值的情况下),如果触摸window,首先由window上最先符合条件的控件(该控件记为hit-test
view)接收到该touch并触发触摸事件touchesBegan。同时如果某个控件的手势识别器接收到了该touch,就会进行识别。手势识别成功之后发送触摸事件touchesCancelled给hit-testview,hit-test
view不再响应touch。
* (2)cancelsTouchesInView:
默认为YES,这种情况下当手势识别器识别到touch之后,会发送touchesCancelled给hit-testview以取消hit-test
view对touch的响应,这个时候只有手势识别器响应touch。
当设置成NO时,手势识别器识别到touch之后不会发送touchesCancelled给hit-test,这个时候手势识别器和hit-test
view均响应touch。
* (3)delaysTouchesBegan:
默认是NO,这种情况下当发生一个touch时,手势识别器先捕捉到到touch,然后发给hit-testview,两者各自做出响应。如果设置为YES,手势识别器在识别的过程中(注意是识别过程),不会将touch发给hit-test
view,即hit-testview不会有任何触摸事件。只有在识别失败之后才会将touch发给hit-testview,这种情况下hit-test
view的响应会延迟约0.15ms。
* (4)delaysTouchesEnded:
默认为YES。这种情况下发生一个touch时,在手势识别成功后,发送给touchesCancelled消息给hit-testview,手势识别失败时,会延迟大概0.15ms,期间没有接收到别的touch才会发送touchesEnded。如果设置为NO,则不会延迟,即会立即发送touchesEnded以结束当前触摸。
*/
演示代码如下,读者自行拷贝尝试
MyViw继承自UIView:
#import "MyView.h" @implementation MyView - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"__begin"); } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"__cancel"); } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"__end"); } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"__touch"); } @end
#import "ViewController.h" #import "MyView.h" @interface ViewController () @property (nonatomic, strong) MyView *myView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; _myView = [[MyView alloc]initWithFrame:CGRectMake(50, 50, [UIScreen mainScreen].bounds.size.width - 100, 200)]; _myView.backgroundColor = [UIColor yellowColor]; [self.view addSubview:_myView]; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)]; tap.numberOfTapsRequired = 2; [_myView addGestureRecognizer:tap]; } - (void)tapAction:(UITapGestureRecognizer *)tap{ NSLog(@"点击"); } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"begin"); } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"cancel"); } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"end"); } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"touch"); } @end