How can I animate the effect of a state change in the view caused by a ViewModel
?
I want to animate the effect of a state change in my View
caused by a call to its ViewModel
. Here’s an example of what I’m trying to achieve:
- Expected behaviour: slow dissolve from blue to red.
- Actual behaviour: immediate change from blue to red.
class ViewModel: ObservableObject {
@Published var color: UIColor = .blue
func change() {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.color = .red
}
}
}
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
Color(viewModel.color)
}
}
How can I animate the change from blue to red when calling viewModel.change()
?