一个渐变到另一个 SwiftUI 的动画过渡

Animation transition of one gradient to another SwiftUI

我试图根据状态值的值来更改背景的渐变,这应该是可能的,而且确实如此。但是,我想为 gradient/background 的这种变化设置动画(当 属性 取决于某些转换时你经常这样做)。所以我尝试设置一个三元运算符,将背景更改为不同的渐变,使用 animation/transition。背景确实发生了变化,但没有平滑的过渡,只是一个生硬的变化。这是我为说明问题而创建的最小工作示例:

import SwiftUI
// Based on https://nerdyak.tech/development/2019/09/30/animating-gradients-swiftui.html

struct ContentView: View {
    @State var animCheck: Bool = false
    
    
    var body: some View {
        VStack {
            Button(action: {
                self.animCheck = true
            }){
                Text("Change gradient")
            }
            Button(action: {
                
            }){
                Text("random button")
                    .background(self.animCheck == true ? LinearGradient(gradient: Gradient(colors: [.white, .green]), startPoint: .leading, endPoint: .trailing).transition(.slide).animation(.spring()) : LinearGradient(gradient: Gradient(colors: [.black, .orange]), startPoint: .leading, endPoint: .trailing).transition(.slide).animation(.spring()) )
            }

        }
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

有什么方法可以绕过 this/create 动画背景更改的预期效果吗? 谢谢

我们需要为容器设置动画以进行转换,所以这是一个解决方案:

Text("random button")
    .background(
        VStack {
            if self.animCheck {
                LinearGradient(gradient: Gradient(colors: [.white, .green]), startPoint: .leading, endPoint: .trailing)
                    .transition(.slide)
            } else {
                LinearGradient(gradient: Gradient(colors: [.black, .orange]), startPoint: .leading, endPoint: .trailing)
                   .transition(.slide)
            }
        }.animation(.spring()))