Navigating a SwiftUI List using arrow keys

354 Views Asked by At

In a Mac SwiftUI project, I have a simple list inside a NavigationView. When I try to navigate using up/down arrow keys, the list will only scroll to one element off the screen in either direction. In other words, in screenshot below, if I click the down arrow, the view will scroll to show element 12, but won't scroll further to show element 13 or beyond(using the arrow keys. It will scroll further using the mouse). Is there a way to correct this so that arrow keys can navigate entire list?

enter image description here


struct ContentView: View {
    var body: some View {
        NavigationView{
            List{
                ForEach((1...100), id: \.self) { id in
                    
                    NavigationLink {
                        Text("Detail View")
                    } label: {
                        Text("\(id)")
                    }
                }
            }
        }
    }
}

Updated: I need to target MacOS 12 so NavigationSplitView isn't an option for me.

1

There are 1 best solutions below

0
On

No related to Mac, but as question that probably brings some devs that try to implement keyboard navigation in Lists on iOS, there's how I managed to do that (let me know if there's a better way).

  1. Create MyController: UIViewController that embeds your MySwiftView: View (that contains a List) in UIHostingController and ads it as a subview. Keep a reference to MySwiftView to pass keyboard events to MySwiftView

  2. Implement support for keyboard commands (e.g. Enter, Escape and Up/down arrows) in MyController. See https://useyourloaf.com/blog/adding-hardware-keyboard-shortcuts/

  3. Pass navigation commands to MySwiftView, and implement navigation logic in MySwiftView (or at the model that MySwiftView uses to display) data.