Consider this view:
This is a simple list, where I can programmatically control the selection, and push another view into the navigation stack. I demonstrate two ways of doing this here, both with a timer and then with a button. Everything works as expected.
Now, when I change the @State variable to @Binding, and pass it in from outside, this suddenly stops working. No matter what I do, I can no longer programmatically change the selection. What’s more, the list UI itself stops working: when I tap on a list item, nothing happens, and no detail view appears.
Why do @State and @Binding behave differently here? Why does navigation link selection work with one, but not the other?
Code Block swift import SwiftUI struct ContentView: View { @State var selection: ListObject? var objects: [ListObject] var body: some View { NavigationView { List { ForEach(objects) { object in NavigationLink( destination: ListObjectView(object: object), tag: object, selection: $selection, label: { Text(object.text) }) } }.listStyle(SidebarListStyle()) .toolbar { ToolbarItem { Button("Push item") { selection = objects.first } } } Text("Empty view, pick something.").padding() }.onAppear { DispatchQueue.main.asyncAfter(deadline: .now() + 2) { selection = objects.first } } } }
This is a simple list, where I can programmatically control the selection, and push another view into the navigation stack. I demonstrate two ways of doing this here, both with a timer and then with a button. Everything works as expected.
Now, when I change the @State variable to @Binding, and pass it in from outside, this suddenly stops working. No matter what I do, I can no longer programmatically change the selection. What’s more, the list UI itself stops working: when I tap on a list item, nothing happens, and no detail view appears.
Why do @State and @Binding behave differently here? Why does navigation link selection work with one, but not the other?