简体   繁体   English

满足条件时 SwiftUI 动画背景颜色变化

[英]SwiftUI animate background color change when a condition is met

I'm trying to change the background color of the Text component, whenever a given condition is met, in this example, when numberOfTaps = 3 , which I'm able to do by having the condition inside the .background property call我正在尝试更改Text组件的背景颜色,只要满足给定条件,在本例中,当numberOfTaps = 3时,我可以通过在.background属性调用中使用条件来做到这一点

What I'm trying to do is to change the background with an animation, nothing too fancy, just something like .easeInOut might work;我想要做的是用动画改变背景,没什么太花哨的,就像.easeInOut类的东西可能会起作用; how can I do that?我怎样才能做到这一点?

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

Here's a sample of the current UI:以下是当前 UI 的示例:

在此处输入图像描述

I have modified your body.我已经改变了你的身体。 Lets try this for easeInOut animation:-让我们试试这个 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")
            }
        }
    }

Note:- You can play with different animation property eg.注意:- 您可以使用不同的动画属性,例如。 easeIn, easeOut etc缓入、缓出等

Wrap your conditions inside the withAnimation{} will automatically apply animation to all the related Views to these conditions/data在 withAnimation{} 中包装您的条件将自动将动画应用于这些条件/数据的所有相关视图

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM