I need your help to understand an issue I'm having. I can't manage to make a view redraws its body just before a transition animation. Take a look at this simple example:
import SwiftUI
struct ContentView: View {
@State private var condition = true
@State private var fgColor = Color.black
var body: some View {
VStack {
Group {
if condition {
Text("Hello")
.foregroundColor(fgColor)
} else {
Text("World")
}
}
.transition(.slide)
.animation(.easeOut(duration: 3))
Button("TAP") {
fgColor = .red
condition.toggle()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
What I expected from this example was: when I tap on the button the view creates its body again and the text "Hello" becomes red. Now, the view creates its body another time and the transition happens. Instead, it seems that SwiftUI merges the two state changes somehow and only the second one is considered. The result is that the transition happens, but the text "Hello" won't change its color.
How can I manage a situation like this in SwiftUI? Is there a way to tell the framework to update the two state changes separately? Thank you.
EDIT for @Asperi:
I tried your code but it doesn't work. The result is still the same. This is the complete example with your code:
import SwiftUI
struct ContentView: View {
@State private var condition = true
@State private var fgColor = Color.black
var body: some View {
VStack {
VStack {
if condition {
Text("Hello")
.foregroundColor(fgColor)
.transition(.slide)
} else {
Text("World")
.transition(.slide)
}
}
.animation(.easeOut(duration: 3))
Button("TAP") {
fgColor = .red
condition.toggle()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
And this is the result (on iPhone 12 Mini iOS 14.1):




