Home > Enterprise >  Transitions not working inside NavigationView
Transitions not working inside NavigationView

Time:07-31

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.

CodePudding user response:

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

CodePudding user response:

This is a tricky question. If you look closely at your code, you see that in postion 3 .transition is applied to the NavigationView. However, in positions 1 & 2 it’s not.

Transitions must be applied to the View that is transitioning, in your case, it’s the NavigationView that is wrapping the content. Implying that the NavigationView needs the modifier.

Add the transition to the NavigationView in any position & it should work as expected.

  • Related