Search code examples
iphonecore-animationuitouch

Recognize the touch event in the moving object


I created a UIImageView dynamically and animating(Moving from one place to another.) in the view. I wrote touch events and trying to recognize the touch on the image view. But it is not able recognize the touch event when that image is animating.

But if I touch on the initial place where I added the image view it is recognizing but while animating touch is not working.

UIImageView *birdImage = [[UIImageView alloc] initWithFrame: CGRectMake(-67, 100, 67, 52)];
birdImage.image = [UIImage imageNamed: @"Flying_bird.png"];
birdImage.tag = 1000;
birdImage.userInteractionEnabled = YES;
[birdImage setContentMode: UIViewContentModeScaleAspectFit];
[self.view addSubview: birdImage];

[UIView animateWithDuration:10.0  delay:0.0 options: ViewAnimationOptionAllowUserInteraction animations:^{ 
          birdImage.frame = CGRectMake(547, 100, 67, 52); 
        } completion:nil];

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
     UITouch *touch = [[event allTouches] anyObject];
     NSLog(@"Tag: %d", [[touch view] tag]);
}

Please any one could help in this.


Solution

  • This will move image from left to right. and on touching image,your touchesBegan method

    calls and you can do anything in your touchesBegan event.

     UIImage *image = [UIImage imageNamed:@"image.png"];
     UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
     imageView.frame = CGRectMake(-1024, 0, 1024, 768);
     [self.view addSubview:imageView];
     [imageView release]; //Your imageView is now retained by self.view
    

    You probably need this method -animateWithDuration:delay:options:animations:completion:. Replace current method with

     [UIView animateWithDuration:10.0
                           delay:0.0
                         options: UIViewAnimationOptionAllowUserInteraction
                      animations:^{
                          imageView.frame = CGRectMake(0, 0, 1024, 768); 
                      }
                      completion:nil];
    

    This should enable touches during the animation.