如何使UIView.animate函数同步?

huangapple go评论50阅读模式
英文:

How to make UIView.animate function to be sync?

问题

我在按钮点击时在我的ViewController中调用animateScan()作为同步函数。因此,在这个函数之后,我调用另一个函数来呈现另一个ViewController。在animateScan()中,我有一个2.5秒的动画,但根据我理解,UIView.animate是异步函数,所以当我调用它时,我只是设置了动画,而animateScan()在不等待这2.5秒的情况下结束了。所以我的问题是,我是否可以以某种方式强制animateScan()函数等待这2.5秒的动画?我能使UIView.animate成为同步的吗?

P.S. 我不想在UIView.animate中使用完成闭包。

英文:

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.

答案1

得分: 0

你不应该将动画设为同步,因为等待其完成会暂停主线程,这是一个非常糟糕的想法。你应该使用完成处理程序。这就是它们存在的原因。

英文:

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.

答案2

得分: 0

你可以将你的方法包装成一个 async 方法:

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

现在,当你在一个 async 上下文中使用 await 调用 animateScan() 时,你的代码会在等待完成之前神奇地暂停并恢复。

英文:

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.

huangapple
  • 本文由 发表于 2023年7月10日 16:03:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76651806.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定