SwiftUI: Animating a transition between two views in a WindowGroup not working

Viewed 231

So I thought it would be easy to transition between the main view of an app and a settings view. The app code looks like this:

struct PointsMasterII: App {

    @StateObject var settings = AppSettings()

    var body: some Scene {
        WindowGroup {
            if settings.displaySettings {
                SettingsView()
                    .environmentObject(settings)
                    .transition(.slide)
            } else {
                ContentView()
                    .environmentObject(settings)
                    .transition(.slide)
            }
        }
    }
}

Which is pretty basic, in each of the views I have the following button defined:


@EnvironmentObject private var settings: AppSettings

var body: some View {

    // ...

    Button {
        withAnimation {
            settings.displaySettings.toggle()
        }
    } label: {
        Image(systemName: "gearshape.2").font(.title)
    }
}

When I run the app and tap the button the two views switch as expected, but without any animation. I've tried a number of things but nothing seems to work and all the tutorials I've found on the interwebs say this should "just work".

Any idea what's missing?

1 Answers

There is no animation modifier, so no animation, try to wrap it in Group or some container (however more appropriate, from design perspective, to move all this into ContentView and separate alternates MainView and SettingsView there)

var body: some Scene {
    WindowGroup {
      Group {      // or VStack
        if settings.displaySettings {
            SettingsView()
                .environmentObject(settings)
                .transition(.slide)
        } else {
            ContentView()
                .environmentObject(settings)
                .transition(.slide)
        }
      }
      .animation(.default, value: settings.displaySettings)
    }
}
Related