I am trying to find the best solution to connect a NSMenuItem with SwiftUI onCommand on macOS.
Currently I an doing the following:
I've been able to get this to work by first making the view focusable
:
struct TestView: View {
let changeColor = #selector(AppDelegate.changeColor(_:))
var body: some View {
VStack {
TextField("Text", text: .constant(""))
Text("Hello World!")
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.focusable() // Add this
.onCommand(changeColor) {
print("Change Color Action")
}
}
}
then you also have to check the "Use keyboard navigation to move focus between controls" checkbox in Keyboard System Preferences