How to make UIView.animate function to be sync?

341 views Asked by At

So I have some function with animation:

func animateScan() {
        topConstraint.constant = frame.height

        UIView.animate(withDuration: 2.5) {
            self.superview?.layoutIfNeeded()
        }
    }

I call animateScan() in my ViewController on button tap as a sync functions. So after this function I call another function to present another ViewController. In animateScan() I have animation with 2.5 duration, but UIView.animate, as I understand Is async function, so when I call it I just setup animation, and animateScan() finishes without waiting this 2.5sec.
So my question is, can I somehow force animateScan() function to wait this 2.5 animation? Can I make UIVIew.animate to be synchronous?

P.S. I don't want to use completion closure in UIview.animate.

2

There are 2 answers

1
matt On BEST ANSWER

You can wrap your method up as an async method:

func animateScan() async {
    await withCheckedContinuation { continuation in
        // ... whatever ...
        UIView.animate(withDuration: 2.5) {
            // ... whatever ...
        } completion: { _ in
            continuation.resume()
        }
    }
}

Now when you call animateScan() by saying await in an async context, your code will magically pause and wait for completion before resuming.

0
Scott Thompson On

You should not make the animation synchronous as waiting for its completion would suspend the main thread and that is a very bad idea. You should use the completion handlers. That's why they exist.