user2569657
user2569657

Reputation: 21

Transition from one view to another in SwiftUI

I have a fairly basic setup but the transition doesn't seem to work. Desired outcome is to fade Loading out and fade Content in. Once the 2 seconds is up and isLoading is set to false it instantly loads the ContentView with no animated transition.

struct MyApp: App { @State private var isLoading = true

var body: some Scene {

    WindowGroup {
        ZStack {
            if isLoading {
                LoadingView()
                    .transition(.opacity)
                    .animation(.easeOut(duration: 2.0), value: isLoading)
            } else {
                ContentView()
                    .transition(.opacity)
                    .animation(.easeIn(duration: 2.5), value: isLoading)

            }
        }
        .onAppear {
            startApp()
        }
    }
}

private func startApp() {
    DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
        isLoading = false
    }
}

}

Have tried a few different approaches though this code seems like the most plausible working solution.

Upvotes: 1

Views: 505

Answers (2)

meomeomeo
meomeomeo

Reputation: 942

animation is how the view animate, not how it transit, that's why it didn't work in the first place. There're many ways to fix your code, such as

  1. Ask the father view to animate
ZStack {
    if isLoading {
        ProgressView()
            .transition(.opacity)
    } else {
        Text("ContentView")
            .transition(.opacity)
    }
}
.animation(.easeOut(duration: 2.0), value: isLoading)
  1. Stop transit the views
ProgressView()
    .opacity(isLoading ? 1 : 0)
    .animation(.easeOut(duration: 2.0), value: isLoading)
Text("ContentView")
    .opacity(isLoading ? 0 : 1)
    .animation(.easeOut(duration: 2.0), value: isLoading)

Upvotes: 0

baohoang
baohoang

Reputation: 788

You should consider replacing

.transition(.opacity)
.animation(.easeIn(duration: 2.5), value: isLoading)

by

.transition(AnyTransition.opacity.animation(.easeInOut(duration: 2.0)))

Upvotes: 0

Related Questions