iosswiftswiftui

Why does withAnimation not cause an animation?


I try to switch from one screen to another by pressing a button (see full code below). The switch from the first view to the second view (and vice versa) works, but no animation is taking place.

Why does this behavior happen?

Full code:

struct ContentView: View {
    @AppStorage("firstViewActive") var isFirstViewActive: Bool = true
    
    var body: some View {
        if isFirstViewActive {
            FirstView()
        } else {
            SecondView()
        }
    }
}

struct FirstView: View {
    @AppStorage("firstViewActive") var isFirstViewActive: Bool = true
    
    var body: some View {
        ZStack {
            Color(.red).ignoresSafeArea(.all, edges: .all)
            VStack {
                Spacer()
                Text("This is the first view")
                Spacer()
                Button {
                    withAnimation {
                        isFirstViewActive = false
                    }
                } label: {
                    Text("Go to second view")
                }
                Spacer()
            }
        }
    }
}

struct SecondView: View {
    @AppStorage("firstViewActive") var isFirstViewActive: Bool = false
    
    var body: some View {
        ZStack {
            Color(.blue).ignoresSafeArea(.all, edges: .all)
            VStack {
                Spacer()
                Text("This is the second view")
                Spacer()
                Button {
                    withAnimation {
                        isFirstViewActive = true
                    }
                } label: {
                    Text("Go to first view")
                }
                Spacer()
            }
        }
    }
}

Solution

  • The problem is with

    @AppStorage("firstViewActive") var isFirstViewActive: Bool = true
    

    If you change that to

    @State var isFirstViewActive: Bool = true
    

    and use @Binding in subviews, you will get the default animations.

    In iOS 16, there seems to be a problem with @AppStorage vars and animation. But you can refer to this workaround