使用Gesture Recognizer
使用Gesture Recognizer识别就会简单许多,只需添加两个手势识别器,分别检测单击和双击事件,设置必要的属性即可。
- - (id)init {
- if ((self = [super init])) {
- self.userInteractionEnabled = YES;
- UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleSingleTap:)];
- singleTapGesture.numberOfTapsRequired = 1;
- singleTapGesture.numberOfTouchesRequired = 1;
- [self addGestureRecognizer:singleTapGesture];
- UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleDoubleTap:)];
- doubleTapGesture.numberOfTapsRequired = 2;
- doubleTapGesture.numberOfTouchesRequired = 1;
- [self addGestureRecognizer:doubleTapGesture];
- [singleTapGesture requireGestureRecognizerToFail:doubleTapGesture];
- }
- return self;
- }
- -(void)handleSingleTap:(UIGestureRecognizer *)sender{
- CGPoint touchPoint = [sender locationInView:self];
- //...
- }
- -(void)handleDoubleTap:(UIGestureRecognizer *)sender{
- CGPoint touchPoint = [sender locationInView:self];
- //...
- }
唯一需要注意的是
- [singleTapGesture requireGestureRecognizerToFail:doubleTapGesture];
这句话的意思时,只有当doubleTapGesture识别失败的时候(即识别出这不是双击操作),singleTapGesture才能开始识别,同我们一开始讲的是同一个问题。
转自:http://www.winddisk.com/2012/10/17/detect_double_tap_single_tap/