简体   繁体   中英

block serial dispatch queue while animating a UIView

Is there a way to manually block a queue task? I want to use UIView animation inside a dispatch queue task, but this task should only get finished when the animation is completed.

dispatch_queue_t myCustomQueue;
myCustomQueue = dispatch_queue_create("com.example.MyCustomQueue", NULL);

dispatch_async(myCustomQueue, ^{
    [UIView animateWithDuration:myDuration
                          delay:0.0f
                        options:0
                     animations:^{
                         // my changes here
                     }
                     completion:nil];
});

dispatch_async(myCustomQueue, ^{
    // if the animation from the task below is still running, this task should wait until it is finished...
});

Suspend your queue using dispatch_suspend and then resume it (using dispatch_resume ) in your animation completion block. This will cause all blocks submitted to the queue to wait for the animation to complete before they are started. Note that blocks already running on that queue when you suspend it will continue running.

  1. Don't make UIView animation calls on anything other than the main thread
  2. If you want something to execute after an animation has completed, put it in the animation's completion block. It's what it is there for.

Problem in Swift 3

I used the following code to execute on the main thread in Swift 3. The animation worked, but the timing was off:

// Animation works, timing is not right due to async
DispatchQueue.main.async {
    // animation code
}

Solution

Updating Sven's answer for Swift 3, I was able to use the following code to get my animation to run properly:

DispatchQueue.main.suspend()
// animation code goes here. 
DispatchQueue.main.resume()

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