UIView animateWithDuration returns immediately

2019-02-19 13:50发布

I'm trying to animate a label embedded in a UIView.

this is the code :

-(void)displayText:(NSString*)text {


[label setText:text];


[UIView animateWithDuration:5.0
                      delay:0.0
                    options:UIViewAnimationOptionCurveEaseIn
                 animations:^{
                     [labelView setAlpha:1.0];
                 }
                 completion:nil
 ];

[UIView animateWithDuration:5.8
                      delay:0.0
                    options:UIViewAnimationOptionCurveEaseIn
                 animations:^{
                     [labelView setAlpha:0.0];
                 }
                 completion:nil
 ];
}

To verify, the method is called, i set a breakpoint.

The calls return immediatly but only the end of animations is displayed.

I wired the UIView to the controller.

Pls help, I'm stuck.

Thanks in advance ! Patrick

1条回答
Bombasti
2楼-- · 2019-02-19 14:35

Correct,

When you animate views like this the animation doesn't actually happen on screen until the next pass of the runloop (i.e. once your method returns).

UIView will coalesce animations that are programmed sequentially.

Use the completion block to fade back out. The code looks a bit odd but it works great!

[UIView animateWithDuration:5.0
                      delay:0.0
                    options:UIViewAnimationOptionCurveEaseIn
                 animations:^{
                     [labelView setAlpha:1.0];
                 }
                 completion:^(BOOL completed){
                     [UIView animateWithDuration:5.8
                                           delay:0.0
                                         options:UIViewAnimationOptionCurveEaseIn
                                      animations:^{[labelView setAlpha:0.0];}
                                      completion:nil];
                 }];

In response to your comments:

The animations won't start until the next run of the runloop. They won't start until your app finishes what its doing. If you wait in the loop you will have the same problem and also freeze up your interface. Consider using individual labels for each letter, and add a progressively bigger delay for each animation. All these animation instructions will be queued up at once and then played out over the course of the next however many seconds. Imagine you are like a movie director, you tell each actor what to do in the next scene. Then, once everyone knows what to do you sit back and yell "action" and watch it all play out.

查看更多
登录 后发表回答