2012-04-25 96 views
4

我有沒有問題,創建幾個自定義UIGestureRecognizers。我決定我想要有一個自定義版本的單擊手勢,並進行了UIGestureRecognizer的子類化。除了一個問題,一切似乎都很好。在我的動作處理函數[gestureRecognizer locationInView:self]中,x和y總是返回零。當我回到UITapGestureRecognizer時,動作處理程序正常工作。這必須是與子類的手勢識別,這裏是我的代碼:創建自定義UIGestureRecognizer

#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 

回答

2

蘋果的文件說:

返回的值是通過計算手勢 一個通用的單點位置UIKit框架。它通常是參與手勢的觸摸 的重心。對於 UISwipeGestureRecognizer和UITapGestureRecognizer類的對象,通過此方法返回的 位置有特殊的 手勢的意義。這個意義是爲那些 類的參考文檔。

因此,我假設每個子類都有自己特殊的這種方法實現,適合自己的專業。所以,你必須實現這個你自己,如果你想繼承UIGestureRecognizer

編輯:

喜歡的東西:

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