简体   繁体   中英

UIView touchesbegan doesn't respond during animation

I have a draggable class that inherits UIImageView. The drag works fine when the view is not animating. But when animating it won't respond to touches. Once the animation is completed the touch works again. But I need it to pause the animation on touches and resume when touch ends. I spent the whole day researching it but couldn't figure out the reason.

Here is my animation code.

[UIView animateWithDuration:5.0f 
  delay:0 
  options:(UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction) 
  animations:^{ 
  self.center = CGPointMake(160,240);
  self.transform = CGAffineTransformIdentity;
  }
  completion:nil
];

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    NSLog(@"touch");
    CGPoint pt = [[touches anyObject] locationInView:self];
    startLocation = pt;
    [self.layer removeAllAnimations];
    [[self superview] bringSubviewToFront:self];
}

That's because ios places your animating view to the target position, when the animation starts, but draws it on the path. So if you tap the view while moving, you actually tap somewhere out of its frame.

In your animating view's init, set userInteractionEnabled to NO. So the touch events are handled by the superview.

self.userInteractionEnabled = NO;

In your superview's touchesBegan method, check your animating view's presentationLayer position. If they match with the touch position, redirect the touchesBegan message to that view.

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    CGPoint point = [[touches anyObject] locationInView:self.view];
    CGPoint presentationPosition = [[animatingView.layer presentationLayer] position];

    if (point.x > presentationPosition.x - 10 && point.x < presentationPosition.x + 10
        && point.y > presentationPosition.y - 10 && point.y < presentationPosition.y + 10) {
        [animatingView touchesBegan:touches withEvent:event];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM