UIView animateWithDuration:delay: working weird

2019-04-29 13:32发布

问题:

I experience a strange problem with iPhone animation blocks. This code:

[UIView animateWithDuration:2 delay: 0 options: 0 animations:
^(void) { [controller setBackgroundColor: [UIColor blueColor]]; }
completion: nil];

[UIView animateWithDuration:2 delay: 2 options: 0 animations:
^(void) { [controller setBackgroundColor: [UIColor redColor]]; }
completion: nil];

Instantly sets the background to red, without passing the blue state. The same thing EVEN for this code:

[UIView animateWithDuration:2 delay: 0 options: 0 animations:
^(void) { [controller setBackgroundColor: [UIColor blueColor]]; }
completion: 

^(BOOL wrwg) {
    [UIView animateWithDuration:2 delay: 2 options: 0 animations:
    ^(void) { [controller setBackgroundColor: [UIColor redColor]]; }
    completion: nil];
}];

That is, where I try to run the second animation AFTER the first has finished. What's the problem?

回答1:

I had the same problem. Make shure that controller is of type UIView otherwise the animation block is interpreted as "no animation to perform" and therefore skipped and the next animation is rendered.

Also have look to this post where I asked the same question (with solution by me): http://www.iphonedevsdk.com/forum/iphone-sdk-development/64451-animation-one-after-another.html#post265531



回答2:

Property backgroundColor is NOT animated in UIView. Instead, use backgroundColor property of the view's layer:

#import <QuartzCore/QuartzCore.h> // don't forget to link this library in project settings

[UIView animateWithDuration:2.0
                      delay:0.0
                    options:UIViewAnimatingOptionBeginFromCurrentState
                 animations:^(void){
                   controller.layer.backgroundColor = [UIColor blueColor].CGColor;
                 }
                 completion:NULL];

P.S. As was pointed in previous posts, make sure that your controller is inherited from UIView. If it is inherited from UIViewController, use controller.view instead.



回答3:

I just had this issue, and I commonly have it. There are two causes, although one is something I have yet to test.

Cause one, I forgot to hook up interface builder to the animated view, thus the block said "Animate on nil? There's nothing to do, so I'm gonna skip to the completion block!"

The other cause is, there is something to do, but it's not an animatable property (Hidden), and I would bet that the completion block is called as soon as the variables in the animation match their "to" or "end" state. It's just a theory, but I'm betting it's a separate thread that executes at a certain pace with: if (currentValueOfProperty = finalValue) doCompletion(). (pardon the pseudo code).

Somebody should probably test that, though