Home > Net >  SwiftUI animate background color change when a condition is met
SwiftUI animate background color change when a condition is met

Time:07-13

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

What I'm trying to do is to change the background with an animation, nothing too fancy, just something like .easeInOut might work; 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:

enter image description here

CodePudding user response:

I have modified your body. Lets try this for easeInOut animation:-

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

CodePudding user response:

Wrap your conditions inside the withAnimation{} will automatically apply animation to all the related Views to these conditions/data

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