subchap
subchap

Reputation: 847

Gesture recognizer for mouse down and up in iPhone SDK

I want to catch both mouse down and mouse up using gesture recognizer. However, when the mouse down is caught, mouse up is never caught.

Here's what I did:

First create a custom MouseGestureRecognizer:

@implementation MouseGestureRecognizer
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {  
    [super touchesBegan:touches withEvent:event];  
    self.state = UIGestureRecognizerStateRecognized;  
}  

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {  
    [super touchesEnded:touches withEvent:event];  
    self.state = UIGestureRecognizerStateRecognized;  
}  
@end  

Then bind the recognizer to a view in view controller:

UIGestureRecognizer *recognizer = [MouseGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];  
[self.view addGestureRecognizer:recognizer];  

When I click mouse in the view, the touchesBegan is called, but touchesEnded is never called. Is it because of the UIGestureRecognizerStateRecognized?

Upvotes: 1

Views: 3598

Answers (2)

fabb
fabb

Reputation: 11735

Maybe you can use a UILongPressGestureRecognizer instead with minimumPressDuration set to 0.

Upvotes: 4

Hejazi
Hejazi

Reputation: 17015

From UIGestureRecognizer class reference for reset method:

The runtime calls this method (reset) after the gesture-recognizer state has been set to UIGestureRecognizerStateEnded or UIGestureRecognizerStateRecognized. (...) After this method is called, the runtime ignores all remaining active touches; that is, the gesture recognizer receives no further updates for touches that have begun but haven't ended.

So, yes, it's because you're setting the state to UIGestureRecognizerStateRecognized in touchesBegan.

EDIT

As a workaround, you can make two recognizers, one for touchesBegan and the other for touchesEnded, and then add both of them to the target view:

UIGestureRecognizer *recognizer1 = [TouchDownGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
UIGestureRecognizer *recognizer2 = [TouchUpGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
[self.view addGestureRecognizer:recognizer1];
[self.view addGestureRecognizer:recognizer2];

Upvotes: 2

Related Questions