代码之家  ›  专栏  ›  技术社区  ›  Frakcool

满足条件时,SwiftUI动画背景颜色更改

  •  0
  • Frakcool  · 技术社区  · 2 年前

    我正在尝试更改 Text numberOfTaps = 3 ,我可以通过在 .background 属性调用

    .easeInOut 可能有效;我该怎么做?

    import SwiftUI
    
    struct ContentView: View {
        @State private var numberOfTaps = 0
        
        var body: some View {
            VStack {
                Button("Up") {
                    numberOfTaps += 1
                }
                
                Text("\(numberOfTaps)")
                    .padding()
                    .background(numberOfTaps == 3 ? Color.blue : Color.green)
                
                Button("Down") {
                    numberOfTaps -= 1
                }
            }
        }
    }
    
    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }
    

    enter image description here

    2 回复  |  直到 2 年前
        1
  •  2
  •   Hussain Shabbir    2 年前

    我已经改变了你的身体。让我们尝试一下easeInOut动画:-

    var body: some View {
            VStack {
                Button {
                    numberOfTaps += 1
                    color = (numberOfTaps == 3) ? Color.blue: Color.green
                } label: {
                    Text("Up")
                }
                Text("\(numberOfTaps)")
                    .padding()
                    .background(color.animation(.easeInOut))
                
                Button {
                    numberOfTaps -= 1
                    color = (numberOfTaps == 3) ? Color.blue: Color.green
                } label: {
                    Text("Down")
                }
            }
        }
    

    注意:-您可以使用不同的动画属性进行播放,例如easeIn,

        2
  •  1
  •   tail    2 年前

    import SwiftUI
    
    struct ContentView: View {
    @State private var numberOfTaps = 0
    
    var body: some View {
        VStack {
            Button("Up") {
                //put your condition inside this wrap
                withAnimation(.easeInOut) {
                    numberOfTaps += 1
                }
            }
            
            Text("\(numberOfTaps)")
                .padding()
                .background(numberOfTaps == 3 ? Color.blue : Color.green)
            
            Button("Down") {
                numberOfTaps -= 1
            }
        }
    }
    }
    
    struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
    }