下面为TouchTracker添加第一个UIGestureRecognizer子类对象:UITapGesture- Recognizer,当用户双击屏幕时,会清除屏幕上的所有线条。打开在第12章中完成的TouchTracker.xcodeproj。
在BNRDrawView.m的initWithFrame:中创建一个UITapGestureRecognizer对象,设置点击次数为2,使BNRDrawView可以识别双击手势:
- (instancetype)initWithFrame:(CGRect)r
{
self = [super initWithFrame:r];
if (self) {
self.linesInProgress = [[NSMutableDictionary alloc] init];
self.finishedLines = [[NSMutableArray alloc] init];
self.backgroundColor = [UIColor grayColor];
self.multipleTouchEnabled = YES;
UITapGestureRecognizer *doubleTapRecognizer =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(doubleTap:)];
doubleTapRecognizer.numberOfTapsRequired = 2;
[self addGestureRecognizer:doubleTapRecognizer];
}
return self;
}
当用户在BNRDrawView上双击时,BNRDrawView会收到doubleTap:消息,在BNRDrawView.m中实现doubleTap::
- (void)doubleTap:(UIGestureRecognizer *)gr
{
NSLog(@“Recognized Double Tap”);
[self.linesInProgress removeAllObjects];
[self.finishedLines removeAllObjects];
[self setNeedsDisplay];
}
双击事件不需要处理消息中传入的UIGestureRecognizer参数,但是本章稍后在处理其他几种手势的动作消息时,会介绍如何从UIGestureRecognizer参数中获取相关信息。
构建并运行应用,在屏幕上画几根线条,然后双击屏幕,所画的线条应该会全部清除。
读者可能会注意到,双击屏幕时,BNRDrawView会在手指双击的位置画出一个红色圆点(在模拟器上看起来更明显)。这个圆点是由BNRDrawView画出的一根很短的线条(当用户点击屏幕时,BNRDrawView会收到touchesBegan:withEvent:消息)。检查控制台中的日志信息,可以看见触摸事件发生的顺序:
touchesBegan:withEvent:
Recognized Double Tap
touchesCancelled:withEvent:
由于UIGestureRecognizer对象会通过截取触摸事件来识别手势,因此,在UIGestureRecognizer对象识别出手势之前,UIView会收到所有UIResponder消息。对于UITapGestureRecognizer来说,在识别出点击手势(在屏幕中的一小块区域触摸并迅速抬起手指)之前,UIView会收到touchesBegan:withEvent:消息;在识别出点击手势之后,UITapGestureRecognizer会自行处理相关触摸事件,由这些触摸事件所引发的UIResponder消息将不会再发送给UIView。直到UITapGestureRecognizer检测出点击手势已经结束,UIView才会重新收到UIResponder消息(touchesCancelled:withEvent:)。
为了去掉红色圆点,需要在识别出点击手势之前避免向UIView发送touchesBegan: withEvent:消息。在BNRDrawView.m中,修改initWithFrame:方法,代码如下:
UITapGestureRecognizer *doubleTapRecognizer =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(doubleTap:)];
doubleTapRecognizer.numberOfTapsRequired = 2;
doubleTapRecognizer.delaysTouchesBegan = YES;
[self addGestureRecognizer:doubleTapRecognizer];
}
return self;
}
构建并运行应用,绘制一些线条,然后双击屏幕清除所有线条,这次应该不会再出现红色圆点了。