I am trying to process the key events inside a NavigationSplitView in SwiftUI, but somehow the NavigationSplitView doesn't pass the events. What am I doing wrong? Thanks for the help!!
This is the code that doesn't work as supposed to, and I'm not sure where to start looking for mistakes:
import SwiftUI
struct ContentView: View {
@State var text:String = ""
var body: some View {
VStack {
HStack{
Text("Works:")
TextField("test1", text: $text).onKeyPress(action: {
a in
print(a.debugDescription)
return .ignored
})
}
NavigationSplitView {
Text("a")
} detail: {
HStack{
Text("Doesnt work")
TextField("test3", text: $text).onKeyPress(action: {
a in
print(a.debugDescription)
return .ignored
})
}
}
}
.padding()
}
}
#Preview {
ContentView()
}
The code is supposed to print the pressed keys for both TextFields.
I didn't find a solution to the problem but a fix. Instead of using the ViewModifier, one could monitor the Events like this (doesn't work in iOS):
.onAppear {keyboardSubscribe()}
private func keyboardSubscribe() {
NSEvent.addLocalMonitorForEvents(matching: .keyDown) { (aEvent) -> NSEvent? in
print(aEvent.keyCode)
return aEvent
}
}