Is it necessary to test the BOOL finished in a completion handler for UIView animation?

后端 未结 2 725
别跟我提以往
别跟我提以往 2021-01-11 09:36

I\'ve never given any thought to the returned BOOL finished of a UIView animation completion handler, but reading some sample code in the Apple UIView Programmi

2条回答
  •  猫巷女王i
    2021-01-11 10:06

    The actual action being undertaken in that code snippet is quite significant. The animation is transitioning from one view to another -- the first is being replaced, and then a boolean is set to keep track of which one is currently displayed. The boolean is set in the completion block.

    [UIView transitionFromView:(displayingPrimary ? primaryView : secondaryView)
        toView:(displayingPrimary ? secondaryView : primaryView)
        duration:1.0
        options:(displayingPrimary ? UIViewAnimationOptionTransitionFlipFromRight :
                    UIViewAnimationOptionTransitionFlipFromLeft)
        completion:^(BOOL finished) {
            if (finished) {
                displayingPrimary = !displayingPrimary;
            }
    }];
    

    In this case, if the animation (for whatever reason) doesn't complete, then the views haven't been exchanged, and you absolutely don't want to flip the value of displayingPrimary, because you'll then have an inaccurate record of your status. That's why the finished flag is checked in this case.

    Notice that in most (if not all) of the other code samples in that guide, the flag isn't checked -- that's because it's not significant in those cases (running another animation after the first, e.g., or changing some value that doesn't depend on the successful completion of the animation).

提交回复
热议问题