Troubles with UIView, animateWithDuration and begi

2019-05-20 23:02发布

问题:

I have a custom view that has to track the user's location. I put the following code in touchesBegan, as well as in touchesMoved:

[UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
    cursorView.center = locationOfTouch;
} completion:^(BOOL finished){}];

It seems fairly straightforward to me. I'd expect the view to always animate to the user's current location, even if that location is changed and the view is still animating (because of the beginFromCurrentState option).

Yet, each animation finishes completely. They don't 'transition' to the new animation, no they finish first, then they start the new animation.

I tried adding this line in touchesMoved:

[cursorView.layer removeAllAnimations];

Doesn't do anything. No animation is cancelled. Any ideas?

回答1:

with [cursorView.layer removeAllAnimations]; you access the layer of the view but you have set the animation not to the layer but the view directly.
Try:

[UIView beginAnimations:nil context:NULL]
[UIView setAnimationDuration:0.2];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
cursorView.center = locationOfTouch;
[UIView commitAnimations];

and leave out the removeAllAnimations and it should transition from current state.



回答2:

Looks like this is a derivative of another question you asked that I just answered, but the same idea applies.

You don't need to use blocks to do this. Just wrap your setCenter in a UIView animation. Like this:

[UIView beginAnimations:nil context:NULL]
[UIView setAnimationDuration:0.2f];
cursorView.center = locationOfTouch;
[UIView commitAnimations];

Keep in mind that 0.2 seconds is pretty fast. It may appear to be "jumping" to the position. To confirm, set the duration to something like 2.0 seconds and see if it's animating.

Best regards.



回答3:

Technically, the view should automatically animate with a default time of 0.25 seconds. That is what the manuals say, however, I'm currently on here because the manuals don't seem to be very accurate regarding animation.

Also, the beginAnimations call is being phased out, you might want to use a CATransaction instead