swiftuiviewanimation

How to make UIView.animate function to be sync?


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.


Solution

  • 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.