2012-07-18 92 views
0

我試圖在documentation中使用複選標記手勢識別器示例,但它僅在第一次做手勢時起作用。承認它後,它不再工作。iOS自定義手勢識別器僅適用於第一次

我用下面的代碼:

CheckmarkGestureRecognizer.h

#import <UIKit/UIKit.h> 
#import <UIKit/UIGestureRecognizerSubclass.h> 

@interface Checkmark2GestureRecognizer : UIGestureRecognizer { 
    BOOL strokeUp ; 
} 


- (void)reset; 
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; 
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; 
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; 
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event; 

@property (nonatomic,readwrite) UIGestureRecognizerState state; 
@property (nonatomic,assign) CGPoint midPoint; 
@end 

CheckmarkGestureRecognizer.m

#import "Checkmark2GestureRecognizer.h" 


@implementation Checkmark2GestureRecognizer 

@synthesize state; 
@synthesize midPoint; 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    [super touchesBegan:touches withEvent:event]; 
      NSLog(@"began"); 
    strokeUp = NO; 
    if ([touches count] != 1) { 
     self.state = UIGestureRecognizerStateFailed; 
     return; 
    } 
} 

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
    [super touchesMoved:touches withEvent:event]; 
    if (self.state == UIGestureRecognizerStateFailed) return; 
    CGPoint nowPoint = [[touches anyObject] locationInView:self.view]; 
    CGPoint prevPoint = [[touches anyObject] previousLocationInView:self.view]; 
    if (!strokeUp) { 
     // on downstroke, both x and y increase in positive direction 
     if (nowPoint.x >= prevPoint.x && nowPoint.y >= prevPoint.y) { 
      self.midPoint = nowPoint; 
      // upstroke has increasing x value but decreasing y value 
     } else if (nowPoint.x >= prevPoint.x && nowPoint.y <= prevPoint.y) { 
      strokeUp = YES; 
     } else { 
      self.state = UIGestureRecognizerStateFailed; 
     } 
    } 
} 

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 
    [super touchesEnded:touches withEvent:event]; 
    if ((self.state == UIGestureRecognizerStatePossible) && strokeUp) { 
     self.state = UIGestureRecognizerStateRecognized; 
      NSLog(@"Ended"); 
    } 

} 

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { 
    [super touchesCancelled:touches withEvent:event]; 
    self.midPoint = CGPointZero; 
    strokeUp = NO; 
    self.state = UIGestureRecognizerStateFailed; 
    NSLog(@"cancelled"); 
} 

- (void)reset { 
    [super reset]; 
    NSLog(@"reset"); 
    self.midPoint = CGPointZero; 
    strokeUp = NO; 
} 

@end 

什麼我做錯了任何想法?

謝謝

回答

2

我自己的手勢識別器有類似的問題。看起來UIGestureRecognizer不會調用你的類的「重置」方法,也不會將「狀態」屬性設置爲UIGestureRecognizerStatePossible。

我知道兩種方法,使其工作:

  1. 你可以自己在touchesEnded方法設置狀態屬性UIGestureRecognizerStatePossible。但這似乎是錯誤的。
  2. 您可以使用UIGestureRecognizer的狀態屬性而不是您自己的狀態。即無處不在使用super.state而不是self.state。
0

嘗試在您的實施中刪除@synthesize state;行。這已經在超類中完成了。

您也不必將UIGestureRecognizerSubclass.h中的所有定義複製到您的頭文件中。最好的是刪除以及。