创建自定义的UIGestureRecognizer

4

我已经创建了几个自定义的UIGestureRecognizers,并且没有任何问题。我决定想要一个自定义版本的单击手势,于是开始子类化UIGestureRecognizer。一切都很好,除了一个问题。在我的操作处理程序中,[gestureRecognizer locationInView:self]始终返回x和y都为零。当我回到UITapGestureRecognizer时,操作处理程序正常工作。这一定与子类化的手势识别器有关,下面是我的代码:

#import "gr_TapSingle.h"

#define tap_Timeout 0.25

@implementation gr_TapSingle


- (id)init
{
    self = [super init];
    if ( self )
    {
    }
    return self;
}

- (void)reset
{
}

-(void)gesture_Fail
{
    self.state = UIGestureRecognizerStateFailed;
}

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    [super touchesBegan:touches withEvent:event];

    if ( [self numberOfTouches] > 1 )
    {
        self.state = UIGestureRecognizerStateFailed;
        return;
    }

    originLocation = [[[event allTouches] anyObject] locationInView:self.view];

    [self performSelector:@selector(gesture_Fail) withObject:nil afterDelay:tap_Timeout];
}

-(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
    [super touchesMoved:touches withEvent:event];

    if ( self.state == UIGestureRecognizerStatePossible )
    {
        CGPoint l_Location = [[[event allTouches] anyObject] locationInView:self.view];
        CGPoint l_Location_Delta = CGPointMake( l_Location.x - originLocation.x, l_Location.y - originLocation.y );
        CGFloat l_Distance_Delta = sqrt( l_Location_Delta.x * l_Location_Delta.x + l_Location_Delta.y * l_Location_Delta.y );
        if ( l_Distance_Delta > 15 )
            self.state = UIGestureRecognizerStateFailed;
        return;
    }
}

-(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
{
    [super touchesEnded:touches withEvent:event];

    if ( self.state == UIGestureRecognizerStatePossible )
        [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(gesture_Fail) object:nil];

    if ( self.state != UIGestureRecognizerStateFailed )
        self.state = UIGestureRecognizerStateEnded;
}

-(void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event
{
    [super touchesCancelled:touches withEvent:event];
    if ( self.state == UIGestureRecognizerStatePossible )
        [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(gesture_Fail) object:nil];
    self.state = UIGestureRecognizerStateFailed;
}

@end
1个回答

2

苹果文档中说:

返回值是UIKit框架计算的通用单点手势位置。它通常是涉及手势的触摸点的质心。对于UISwipeGestureRecognizer和UITapGestureRecognizer类的对象,此方法返回的位置具有与手势相关的特殊意义。这些特殊意义在这些类的参考文献中有所记录。

因此,我认为每个子类都有自己特殊的实现方式,以适应其各自的特点。因此,如果要创建UIGestureRecognizer的子类,则必须自己实现此方法。

编辑:

类似以下内容:

- (CGPoint)locationInView:(UIView *)view
{
   if(view == self.view)
   {
      return originLocation;
   }
   else
   {
     //you decide
   }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接