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
4

1 回答 1

2

苹果的文档说:

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

所以我假设每个子类都有它自己的这个方法的特殊实现,适合它自己的专长。所以如果你想子类化,你必须自己实现它UIGestureRecognizer

编辑:

就像是:

- (CGPoint)locationInView:(UIView *)view
{
   if(view == self.view)
   {
      return originLocation;
   }
   else
   {
     //you decide
   }
}
于 2012-04-25T17:35:29.513 回答