'Why does a SwiftUI TextField inside a navigation bar only accept input one character at a time

I want to allow the user to filter data in a long list to more easily find matching titles.

I have placed a TextView inside my navigation bar:

.navigationBarTitle(Text("Library"))
.navigationBarItems(trailing: TextField("search", text: $modelData.searchString)

I have an observable object which responds to changes in the search string:

class DataModel: ObservableObject {
   @Published var modelData: [PDFSummary]
   @Published var searchString = "" {
            didSet {
                if searchString == "" {
                    modelData =  Realm.studyHallRealm.objects(PDFSummary.self).sorted(by: { $0.name < $1.name })
                } else {
                    modelData =  Realm.studyHallRealm.objects(PDFSummary.self).sorted(by: { $0.name < $1.name }).filter({ $0.name.lowercased().contains(searchString.lowercased()) })
                }
            }
        }

Everything works fine, except I have to tap on the field after entering each letter. For some reason the focus is taken away from the field after each letter is entered (unless I tap on a suggested autocorrect - the whole string is correctly added to the string at once)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source