KISS

Keep It Simple Stupid

Weird delay of UIView's animation

| comments

Why a UIView’s animation may be delayed?

I had this issue recently that the animation I wanted to run would start 5 seconds later without any apparent reason:

1
2
3
4
5
6
7
8
9
- (void)barDidBaz {
    [self foo];
}

- (void)foo {
    [UIView animateWithDuration:1.0f animations:^{
        self.imageView.alpha = 0.0f;
    }];
}

It turned out that the barDidBaz method was run not on the main thread, and thus the main dispatch queue (because it was called as a delegate’s method from a socket handler in another dispatch queue), that’s why the animation was delayed. Apparently, another UI event did trigger the animation in the end.

The fix is very simple here:

1
2
3
4
5
- (void)barDidBaz {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self foo];
    });
}

We request to invoke the foo method in the main, UI dispatch queue. Another option is to wrap the call to barDidBaz into that dispatch_async(dispatch_get_main_queue(), ^{ /*…*/ }) block. BTW, do you use blocks in Objective-C? You should.

dev, iOS

Don't hesitate to leave a comment below. NB! If you don't see a comment form under the post, it's most likely that an extension (such as Ghostery, NoScript, or AdBlock) of your browser blocks the scripts from disqus.com, and you can unblock that.

« Don't update while updating! Bash/zsh: edit latest command »

Comments