Transitions not working inside NavigationView

I am trying to navigate between two views without a NavigationLink.

Here is the code:


import SwiftUI

struct NextView: View {
    
    @State var text = ""
    @Binding var displayView: Bool
    
    var body: some View {
        // 3
        //NavigationView {
            VStack {
                Spacer()
                TextField("Type something!", text: $text)
                Button("Remove View") {
                    withAnimation {
                        displayView = false
                    }
                }
                Spacer()
            }.background(Color.cyan)
        //}
    }
}

struct InitialView: View {
    
    @State var displayView = false
    
    var body: some View {
        // 1
        //NavigationView {
            if displayView {
                //2
                //NavigationView {
                    NextView(displayView: $displayView)
                        .transition(.slide)
                
                //}
            } else {
                Button("Tap to continue") {
                    withAnimation {
                        displayView = true
                    }
                }
            }
        //}
    }
}

I tried to place the NavigationView in 3 different places, one at a time. I managed to get the animation I wanted only by placing the structure in position 3 or not using it. Could anyone tell me why this happens and other possible solutions to use the NavigationView in position 1?

I tested only in the iPhone 12 simulator and am using XCode Version 13.4.1.

>Solution :

I think you just wanted this – animatable transition

struct InitialView: View {

    @State var displayView = false

    var body: some View {
        NavigationView {   // << just root view, not important
            ZStack {                  // << owner container !!
                if displayView {
                    NextView(displayView: $displayView)
                        .transition(.slide)
                } else {
                    Button("Tap to continue") {
                        displayView = true
                    }
                }
            }
            .animation(.default, value: displayView)   // << animation !!
        }
    }
}

Tested with Xcode 13.4 / iOS 15.5

Leave a Reply