Home > Back-end >  Simple transition animation not working in SwiftUI
Simple transition animation not working in SwiftUI

Time:07-19

I am trying to understand transition animations in SwiftUI and it just doesn't work for me. In the following code, the transition after one second is immediate (no fade).

struct TestApp: App {
    
    @State private var isReady: Bool = false
    
    var body: some Scene {
        WindowGroup {
            if isReady {
                Color.red
            } else {
                Color.blue
                    .transition(.opacity)
                    .onAppear {
                        DispatchQueue.main.asyncAfter(deadline: .now()   1) {
                            withAnimation {
                                isReady = true
                            }
                        }
                    }
            }
        }
    }
}

CodePudding user response:

Transition and animation are different things, there is a view to be shown with transition and there is a view that animates this transition. Also app does not update view, a state should be inside view.

So here is a correct variant:

struct TestApp: App {
    var body: some Scene {
        WindowGroup {
          ContentView()  // root view of the scene !!
        }
    }
}

struct ContentView: View {
    // state of the view refreshes the view
    @State private var isReady: Bool = false

    var body: some View {
       ZStack {           // animating container !!
            if isReady {
                Color.red
//                    .transition(.opacity)  // probably you wanted this as well
            } else {
                Color.blue
                    .transition(.opacity)  // << transition here !!
            }
        }
        .onAppear {   // << responsible for animation !!
            DispatchQueue.main.asyncAfter(deadline: .now()   1) {
                withAnimation {
                    isReady = true
                }
            }
        }
    }
}
  • Related