CodexBloom - Programming Q&A Platform

SwiftUI Navigation Link Not Preserving State on iOS 17 When Pushing Views

๐Ÿ‘€ Views: 63 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-28
swift swiftui ios navigation Swift

I've encountered a strange issue with I've been struggling with this for a few days now and could really use some help. I'm working on a SwiftUI application that utilizes `NavigationLink` to push views on iOS 17. However, I noticed that when I navigate back and forth between views, the state of the previous view is not preserved as expected. For instance, I have a form with several fields, and after going back to it, all the inputs are reset to their initial values instead of retaining what the user entered. Hereโ€™s a simplified version of the code Iโ€™m using: ```swift struct ContentView: View { @State private var name: String = "" @State private var age: String = "" var body: some View { NavigationView { Form { TextField("Name", text: $name) TextField("Age", text: $age) NavigationLink(destination: DetailView(name: $name, age: $age)) { Text("Go to Details") } } .navigationTitle("Profile") } } } struct DetailView: View { @Binding var name: String @Binding var age: String var body: some View { VStack { Text("Name: \(name)") Text("Age: \(age)") } .navigationTitle("Details") } } ``` When I navigate to the `DetailView` and go back to `ContentView`, the input fields are cleared. I tried using `@State` and `@Binding` but it still doesnโ€™t seem to work. Additionally, I verified that the data flow is correct, as the initial values are displayed correctly in the `DetailView`. I also checked if the `NavigationView` is being recreated, but I am using the same `ContentView` instance, so I expect the state to persist. Have I missed something, or is there a different way to manage state in SwiftUI for this use case? Any help would be greatly appreciated. The stack includes Swift and several other technologies.