CodexBloom - Programming Q&A Platform

SwiftUI NavigationLink Not Preserving State When Popped Back Using UINavigationController

👀 Views: 339 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-03
swift swiftui navigation Swift

I'm refactoring my project and I'm working with an scenario with SwiftUI where a `NavigationLink` does not seem to preserve the state of the view when I navigate back using a `UINavigationController`... Specifically, I'm using SwiftUI 2.0 and iOS 15.0. The view I'm navigating to has a form that the user can fill out, and I'm managing the state using `@State`. When I return to the previous view, the form values reset instead of maintaining their state. Here's a simplified version of my implementation: ```swift struct MainView: View { var body: some View { NavigationView { NavigationLink(destination: DetailView()) { Text("Go to Detail") } .navigationBarTitle("Main View") } } } struct DetailView: View { @State private var name: String = "" @State private var age: String = "" var body: some View { Form { TextField("Name", text: $name) TextField("Age", text: $age) } .navigationBarTitle("Detail View", displayMode: .inline) } } ``` When I navigate to `DetailView` and fill in the text fields, if I go back to `MainView` and then navigate to `DetailView` again, the text fields are reset to empty strings. I expected the state to continue since I'm using `@State`. I've tried moving to a `@StateObject` or `@ObservedObject` with a view model to manage the state, but the scenario continues. Also, I've verified that the `NavigationView` is not being recreated; it remains in the same view hierarchy. Has anyone else experienced this question, or does anyone know how to ensure that the state is preserved when navigating back and forth? Any insights would be greatly appreciated! I recently upgraded to Swift stable.