Reputation: 804
I'm having some troubles with long press gesture here. I've look around and found some post related to my issues, but no luck until now.
I have a long press gesture for a view, and I want to show an alert view when the gesture is trigger, but somehow the trigger got called twice when the alert view is shown, I've check the state of the gesture recognizer but still no luck. Here the code:
Initial code:
UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
[longTap setMinimumPressDuration:1];
[self addGestureRecognizer:longTap];
- (IBAction)handleTapGesture:(UIPanGestureRecognizer*)sender {
if (sender.state == UIGestureRecognizerStateChanged) {
NSLog(@"Change");
} else if (sender.state == UIGestureRecognizerStateEnded) {
NSLog(@"Ended");
}
else {
NSLog(@"Begin");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Long pressed" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show]; //If I remove this line, the trigger is call only once.
}
}
The wierd thing is, if I remove the [alert show], everything goes as expected, the gesture is trigger only once. Anyone has the explanation for this? Thanks in advance.
Upvotes: 4
Views: 1200
Reputation: 798
Please use below code for your solution.
UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
[longTap setMinimumPressDuration:1];
longTap.delegate = (id)self;
[self.view addGestureRecognizer:longTap];
- (void)handleTapGesture:(UILongPressGestureRecognizer *)sender
{
if (sender.state == UIGestureRecognizerStateChanged)
{
NSLog(@"Change");
}
else if (sender.state == UIGestureRecognizerStateEnded)
{
NSLog(@"Ended");
}
else if (sender.state == UIGestureRecognizerStateBegan)
{
NSLog(@"Begin");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Long pressed" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show]; //If I remove this line, the trigger is call only once.
}
}
Upvotes: 5