I have the following view.
import SwiftUI
struct AppView: View {
@EnvironmentObject var appStore: AppStore
var body: some View {
ZStack {
Color.blue
if .game == self.appStore.appMode {
GameView()
} else if .options == self.appStore.appMode {
OptionsView()
} else {
MenuView()
}
}
}
}
I want to animate the switching between the child views.
I have seen some examples using a state for one switch, but I'm relying on more than one.
I also tried to apply the animation inside a child view with onAppear and onDisappear. That works, but when the view is not shown, the onDisappear does not get executed anymore. Besides, I would like to make it work for all the views.
Is there any way to do this without using multiple states? I would love to use only .transition and .animation.
Right now my best solution is this.
import SwiftUI
struct AppView: View {
@EnvironmentObject var appStore: AppStore
var body: some View {
ZStack {
Color.blue
if .game == self.appStore.appMode {
GameView()
.transition(.scale)
.zIndex(1) // to keep the views on top, however this needs to be changed when the active child view changes.
} else if .options == self.appStore.appMode {
OptionsView()
.transition(.scale)
.zIndex(2)
} else {
MenuView()
.transition(.scale)
.zIndex(3)
}
}
}
}
And on every view changer.
.onTapGesture {
withAnimation(.easeInOut(duration: 2)) {
self.appStore.appMode = .game
}
}

