在 SwiftUI 中链接动画 [英] Chaining animations in SwiftUI

查看:23
本文介绍了在 SwiftUI 中链接动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 SwiftUI 中处理一个相对复杂的动画,并且想知道链接各个动画阶段的最佳/最优雅的方式是什么.

I'm working on a relatively complex animation in SwiftUI and am wondering what's the best / most elegant way to chain the various animation phases.

假设我有一个视图,它首先需要缩放,然后等待几秒钟然后消失(然后等待几秒钟并重新开始 - 无限期).

Let's say I have a view that first needs to scale, then wait a few seconds and then fade (and then wait a couple of seconds and start over - indefinitely).

如果我尝试在同一个视图/堆栈上使用多个 withAnimation() 块,它们最终会相互干扰并弄乱动画.

If I try to use several withAnimation() blocks on the same view/stack, they end up interfering with each other and messing up the animation.

到目前为止我能想到的最好的方法是在初始视图 .onAppear() 修饰符上调用一个自定义函数,在该函数中,为动画的每个阶段使用 withAnimation() 块,它们之间有延迟.所以,它基本上看起来像这样:

The best I could come up with so far, is call a custom function on the initial views .onAppear() modifier and in that function, have withAnimation() blocks for each stage of the animation with delays between them. So, it basically looks something like this:

func doAnimations() {
  withAnimation(...)

  DispatchQueue.main.asyncAfter(...)
    withAnimation(...)

  DispatchQueue.main.asyncAfter(...)
    withAnimation(...)

  ...

}

它最终很长而且不是很漂亮".我确信必须有更好/更好的方法来做到这一点,但到目前为止我尝试的一切都没有给我我想要的确切流程.

It ends up being pretty long and not very "pretty". I'm sure there has to be a better/nicer way to do this, but everything I tried so far didn't give me the exact flow I want.

任何想法/建议/提示将不胜感激.谢谢!

Any ideas/recommendations/tips would be highly appreciated. Thanks!

推荐答案

如其他回复中所述,目前 SwiftUI 中没有链接动画的机制,但您不一定需要使用手动计时器.相反,您可以在链接的动画上使用 delay 函数:

As mentioned in the other responses, there is currently no mechanism for chaining animations in SwiftUI, but you don't necessarily need to use a manual timer. Instead, you can use the delay function on the chained animation:

withAnimation(Animation.easeIn(duration: 1.23)) {
    self.doSomethingFirst()
}

withAnimation(Animation.easeOut(duration: 4.56).delay(1.23)) {
    self.thenDoSomethingElse()
}

withAnimation(Animation.default.delay(1.23 + 4.56)) {
    self.andThenDoAThirdThing()
}

我发现与使用 DispatchQueueTimer 相比,这会产生更一致、更流畅的链接动画,可能是因为它对所有动画使用相同的调度程序.

I've found this to result in more consistently smoother chained animations than using a DispatchQueue or Timer, possibly because it is using the same scheduler for all the animations.

处理所有延迟和持续时间可能会很麻烦,因此雄心勃勃的开发人员可能会将计算抽象为一些全局 withChainedAnimation 函数,而不是为您处理.

Juggling all the delays and durations can be a hassle, so an ambitious developer might abstract out the calculations into some global withChainedAnimation function than handles it for you.

这篇关于在 SwiftUI 中链接动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆