I'm trying to build a dialog where the user can select from one or more of (currently) four lists. Since each list is structured similarly, I'm building a view that will be used by each of the lists. The lists can potentially have thousands of entries, so I'd like to allow the user to filter the list by typing into a search field (which in SwiftUI would be just a TextField) and only showing the matching entries. This is all working with the code below, but I can't select a row of the list.
I'm still wrapping my mind around the paradigm shift to SwiftUI, so I may well be missing something obvious.
Further down the track, I need to pass the selected item up to the dialog, and preferably send an initial selection to the list. I assume that is done by making the selection a binding to the appropriate state variable in the enclosing view and setting the selection, presumably in a .onAppear clause. Any pointers there would be welcome, too!
Code Block Swift struct RegistryEntry: Equatable, Identifiable, Hashable { var id = UUID() var code = "" var name = "" var other = "" } struct RegistryPicker: View { @State var sourceList: [RegistryEntry] @State var searchString = "" @State var selectedCode: String @State private var selectedItem: RegistryEntry? var body: some View { HStack() { VStack() { TextField("Filter", text: $searchString) Spacer() } List(searchString == "" ? sourceList : sourceList.filter { $0.name.localizedCaseInsensitiveContains(searchString) }, selection: $selectedItem) { entry in Text(entry.name) } } }
I'm still wrapping my mind around the paradigm shift to SwiftUI, so I may well be missing something obvious.
Further down the track, I need to pass the selected item up to the dialog, and preferably send an initial selection to the list. I assume that is done by making the selection a binding to the appropriate state variable in the enclosing view and setting the selection, presumably in a .onAppear clause. Any pointers there would be welcome, too!
I eventually figured out that the important thing I was missing was "id: \.self" in the List statement. I'd understood the documentation to say that wasn't necessary if the content conformed to Identifiable, but I was mistaken, and you need to specify the identifier.
Your solution is interesting, and worth thinking about as I continue to work on the project.
Your solution is interesting, and worth thinking about as I continue to work on the project.