Search code examples
iphonecocoauiviewtouchuiviewanimation

Detect Touch on an animated View


I'm animating a couple of views with animateWithDuration: and i'm simply unable to detect any touches on them.

I've tried simple touch handling (touchesEnded:) and a tapGestureRecognizer.

First i've animated them with CGAffineTransformTranslation but then i realized that this won't if i check the coordinate with touchesMoved: so i switched to animate the frame property. I quickly noticed, that the frame values are not really changing during the animation so i dropped the touchesEnded: idea. So i changed to a tapGestureRecognizer which doesn't work too.

I've enabled userInteraction on all views and i also added the option UIViewAnimationOptionAllowUserInteraction to the animation.

Here's the code of the animation and the stuff that happens before:

// init the main view
singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapOnItem:)]; // singleFingerTap is an ivar

// code somewhere:
// userItem is a subview of MainView
[userItem addGestureRecognizer:singleFingerTap];

[UIView animateWithDuration:animationTime
                      delay:0.0f
                    options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction
                 animations:^{
                     userItem.frame = CGRectMake(-(self.bounds.size.width + userItem.frame.size.width), userItem.frame.origin.y, userItem.frame.size.width, userItem.frame.size.height);
                 }

                 completion:^(BOOL finished) {
                     if (finished) {
                         [unusedViews addObject:userItem];
                         [userItem removeFromSuperview];
                         [userItem removeGestureRecognizer: singleFingerTap];
                     }
                 }
 ];

And here's the gesture recognizer:

- (void) handleTapOnItem:(UITapGestureRecognizer *)recognizer{
   NSLog(@"Touched");
}

So how can i actually get a touch from an animated View or what is the best solution? Adding transparent uibutton to each view is not an option. :(


Solution

  • When an animation is applied to a view, the animated property changes to its end value right away. what you are actually seeing on screen is the presentation layer of your views layer.

    I wrote a blog post about hit testing animating views/layers a while back that explain it all in more detail.