I'd like to use a SwiftUI TextField
and a SwiftUI List
to render a "search box" above a list of items. Something roughly like the search box available in Safari's Help menu item...which provides a search box where you can always enter text while simultaneously browsing through the list of results using the up and down arrow keys.
I've played with onMoveCommand
, focusable
, and adjustments to the "parent" NSWindow
, but haven't found a clear and obvious way for the TextField
to constantly accept input while still being able to navigate the underlying List
using the up and down arrow keys. The following code allows for either text to be entered in the TextField
, or list entries to be navigated through, but not both at the same time...
struct ContentView: View {
@State var text: String = ""
@State var selection: Int? = 1
var body: some View {
VStack {
TextField("Enter text", text: $text)
List(selection: $selection) {
ForEach((1...100), id: \.self) {
Text("\($0)")
}
}
}
}
}
You can wrap a NSTextField in a NSViewRepresentable and use the NSTextFieldDelegate to intercept the move up and down keys. You can take a look into my suggestions demo.
Source of a text field with suggestions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With