简体   繁体   中英

iPhone - is there any advantage in using animateWithDuration instead of UIView beginAnimations?

One simple question:

This is an example of an old fashion animation:

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];

[base setTransform:rotate];
[base setCenter:newCenter];

[UIView commitAnimations];

this can be written like

[UIView animateWithDuration:0.5 animations:^{

[base setTransform:rotate];
[base setCenter:newCenter];

}];

is there any advantage in rewriting the animation using this new form?

There should be some kind of gain, or Apple would not make this new function.

What do you guys say?

Apple made the change not for performance, but because blocks are an easier way to express this kind of thing. Previously you'd have to use selectors to be triggered when an animation finished, etc.

So - why to use animateWithDuration : because blocks save time, make code cleaner, and are just generally very useful.

And why to use beginAnimation : because you want to support versions of iOS prior to 4.0, where that code isn't available. Apple still need to provide both methods because they need to remain backwards compatible - but the documentation strongly recommends you use the blocks version of methods where available and appropriate.

I think animateWithDuration is newer and look better. I use it more than beginAnimation . It is more clear code. beginAnimation use when you need compatible for iOS version less than 4.0.

But in some case, beginAnimation has more advantage , make easier when you write a function with a parameter animated . Example:

- (void)moveSomethingWithAnimated:(BOOL)animated {

    // Do other task 1

    if( animated ) {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.2];

        someView.frame = newFrame;
        otherView.frame = newFrame;
    }

    if( animated ) {
        [UIView commitAnimations];
    }

    // Do other task 2
}

Instead of:

- (void)moveSomethingWithAnimated:(BOOL)animated {

    // Do other task 1

    if( animated ) {
        [UIView animateWithDuration:0.2 animations:^{
            someView.frame = newFrame;
            otherView.frame = newFrame;
        }];
    }
    else {
        // duplicate code, or you have to write another function for these two line bellow
        someView.frame = newFrame;
        otherView.frame = newFrame;
    }

    // Do other task 2
}

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