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

查看:149
本文介绍了在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()
}

我发现这会导致更多与使用 DispatchQueue Timer 相比,始终保持链接动画的平滑性更好,这可能是因为它对所有动画使用了相同的调度程序。

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.

弄乱所有延迟和持续时间可能很麻烦,因此,雄心勃勃的开发人员可能会使用ChainedAnimation c>函数胜于为您处理。

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天全站免登陆