SwiftUI - How to use onCommand with NSMenuItem on macOS

前端 未结 2 831
悲&欢浪女
悲&欢浪女 2021-02-06 07:42

I am trying to find the best solution to connect a NSMenuItem with SwiftUI onCommand on macOS.

Currently I an doing the following:

  1. In AppDelegate I create
2条回答
  •  迷失自我
    2021-02-06 08:32

    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

提交回复
热议问题