链接的动画因方向改变而混乱

时间:2020-08-24 06:52:40

标签: swift animation layout swiftui

当我改变方向时,闪烁的SF符号开始上下移动。上下动画仅应实现一次(外观上)。但是,我尝试使用verticalSizeClass,这无济于事。

工作原理:在外观上,文本和SF符号向上移动,然后Sparkle SF符号向上和向下缩放。

这是它在方向改变时的外观和行为:

enter image description here

struct ContentView: View {
    @State private var offsetY: CGFloat = 150
    @State private var opacityAmount: Double = 0
    @State private var animationAmount: CGFloat = 1
    
    var body: some View {
        VStack {
            HStack {
                Image(systemName: "sparkle").foregroundColor(.yellow)
                    .offset(y: offsetY)
                    .opacity(opacityAmount)
                    .animation(
                        Animation.easeOut(duration: 0.5).delay(0.1)
                    )
                    .scaleEffect(animationAmount)
                    .animation(Animation.easeInOut(duration: 1).repeatForever(autoreverses: true))
                Text("All new design").font(.largeTitle)
                    .offset(y: offsetY)
                    .opacity(opacityAmount)
                    .animation(
                        Animation.easeOut(duration: 0.5).delay(0.1)
                    )
            }
            .onAppear {
                offsetY = 0
                opacityAmount = 0.8
                animationAmount = 2
            }
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您没有根据我先前的回答改编动画值联接,并观察了结果。

这是因为.animation修饰符引入了隐式动画,该动画被应用于其上方的 all 动画视图修饰符,可能最终导致不希望的累积多个动画(当然,有时候是需要的。)

这是固定的部分。经过Xcode 12 / iOS 14的测试

HStack {
    Image(systemName: "sparkle").foregroundColor(.yellow)
        .offset(y: offsetY)
        .opacity(opacityAmount)
        .animation(
            Animation.easeOut(duration: 0.5).delay(0.1)
        , value: opacityAmount)                     // << here !!
        .scaleEffect(animationAmount)
        .animation(Animation.easeInOut(duration: 1).repeatForever(autoreverses: true),
            value: animationAmount)                // << here !!
    Text("All new design").font(.largeTitle)
        .offset(y: offsetY)
        .opacity(opacityAmount)
        .animation(
            Animation.easeOut(duration: 0.5).delay(0.1)
        , value: opacityAmount)                           // << here !!
}

注意:您可以使用哪个动画赋予或不赋予其明确的价值。