Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI macOS Scroll a List With Arrow Keys While a TextField is Active

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.

safari help menu item

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)")
        }
      }
    }
  }
}
like image 239
David Muller Avatar asked Jan 16 '20 06:01

David Muller


1 Answers

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

like image 134
Stephan Michels Avatar answered Sep 28 '22 14:09

Stephan Michels