2

我试图根据状态值的值来改变背景的梯度,这应该是可能的,而且确实如此。但是,我想对渐变/背景的这种变化进行动画处理(当属性依赖于某些过渡时,您通常会这样做)。所以我尝试设置一个三元运算符,将背景更改为不同的渐变,并带有动画/过渡。背景确实发生了变化,但没有平滑的过渡,只是一种剧烈的变化。这是我为说明问题而创建的最小工作示例:

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()
    }
}

有没有办法解决这个问题/在这里创建动画背景变化的预期效果?谢谢。

4

1 回答 1

2

我们需要对容器进行动画处理以使过渡工作,所以这里有一个解决方案:

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()))
于 2021-01-07T05:45:47.340 回答