I am trying to find the best solution to connect a NSMenuItem with SwiftUI onCommand on macOS.
Currently I an doing the following:
@IBAction func changeColor(_ sender: Any) {
print("Dummy Function")
}
Create and connect a NSMenuItem with the First Responder function in the Main.storyboard.
Add the required code to my SwiftUI view
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)
.onCommand(changeColor) {
print("Change Color Action")
}
}
}
If the TextField was First Responder before I will see that "Change Color Action" is printed. The View will not become First Responder if the TextField was not First Responder before. Maybe this is currently a bug in Catalina Beta (19A558d) since I don't get focusable to work as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With