I am trying to find the best solution to connect a NSMenuItem with SwiftUI onCommand on macOS.
Currently I an doing the following:
I ended up creating a PassthroughSubject
in my AppDelegate, passing it through to my SwiftUI view, and subscribing to it in the model object owned by my SwiftUI view. When my AppDelegate selector for the menu command is called, I send the event using the PassthroughSubject
, which my model receives and handles appropriately.
My answer is definitely not ideal, and I'd love to know if you figure out a better way to do this.
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