swiftswiftuiswiftui-navigationstackswiftui-navigationsplitview

SwiftUI TextField mysteriously breaks navigation animation when used with NavigationPath


MRE

enum HomeDestination: Int, CaseIterable, Hashable, Identifiable {
    case a
    var id: Int { rawValue }
    var name: String {
        switch self {
        case .a: return "A"
        }
    }
}

class NavCordinator: ObservableObject {
    @Published var navMenu = NavigationPath()
}

struct Popup : View {
    @State var text: String = ""
    var body: some View {
        VStack {
            TextField("Text", text: $text)
        }
    }
}
struct ContentView: View {
    @State private var selectedMenu: HomeDestination?
    @StateObject private var navCord: NavCordinator = NavCordinator()
    @State var showCreate = false

    var body: some View {
        NavigationSplitView {
            VStack {
                List(HomeDestination.allCases, selection: $selectedMenu) { menu in
                    NavigationLink(value: menu) {
                        Text(menu.name)
                    }
                }
                ZStack {
                    Button("Create") {
                        showCreate.toggle()
                    }
                }
            }
            .sheet(isPresented: $showCreate) {
                Popup()
            }

        } detail: {
            NavigationStack(path: $navCord.navMenu) {
                switch selectedMenu {
                case .a:
                    Text("A")
                case .none:
                    Text("hi")
                }
            }
        }
    }
}

If you run that code and show the modal first, and then try to push the nav stack you will see the animation breaks.

The animation will come back by changing one of the two changes:

  1. Change TextField to a regular Text() in the modal or
  2. Move the NavigationPath() to become a state of ContentView instead of a published variable

But I don't understand what is breaking it and how to fix it because I need it to be a stateObject (so that it can be shared to other views) and I also need TextField


Solution

  • An answer was provided in another forum. Basically this bug is gone if you move .sheet to the top level of NavigationSplitView