Question

Are there known issues with gesture recognizers and the UIView class methods for animation?

I am having problems with a sequence of animations on a UIImageView from UIGestureRecognizer callback. If the sequence of animations is started from a standard callback like TouchUpInside, the animation works fine. If it is started via the UILongPressGestureRecognizer, then the first animation jumps to the end and the second animation immediately begins.

Here's a sample that illustrates my problem. In the .xib for the project, I have a UIImageView that is connected to the viewToMove IBOutlet. I also have a UIButton connected to the startButton IBOutlet, and I have connected its TouchUpInside action to the startButtonClicked IBAction. The TouchUpInside action works as I want it to, but the longPressGestureRecognizer skips to the end of the first animation after about half a second. When I NSLog the second animation (animateTo200) I can see that it is called twice when a long press starts the animation but only once when the button's TouchUpInside action starts the animation.

- (void)viewDidLoad {
[super viewDidLoad];

UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(startButtonClicked)];
NSArray *recognizerArray = [[NSArray alloc] initWithObjects:longPressRecognizer, nil];
[startButton setGestureRecognizers:recognizerArray];

[longPressRecognizer release];
[recognizerArray release];
}

-(IBAction)startButtonClicked {

if (viewToMove.center.x < 150) {
    [self animateTo200:@"Right to left" finished:nil context:nil];
} else {
    [self animateTo100:@"Right to left" finished:nil context:nil];
}
}

-(void)animateTo100:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
[UIView beginAnimations:@"Right to left" context:nil];
[UIView setAnimationDuration:4];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animateTo200:finished:context:)];
viewToMove.center = CGPointMake(100.0, 100.0);
[UIView commitAnimations];          
}

-(void)animateTo200:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
[UIView beginAnimations:@"Left to right" context:nil];
[UIView setAnimationDuration:4];
viewToMove.center = CGPointMake(200.0, 200.0);
[UIView commitAnimations];          
}
Was it helpful?

Solution

You should change the signature of startButtonClicked to - (void)startButtonClicked:(UIGestureRegognizer *)gestureRecognizer and then query the gesture recognizer's state property in the method. The gesture recognizer will call its action method multiple times with different states (e.g. UIGestureRecognizerStateBegan and UIGestureRecognizerStateEnded).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top