如何在 Swift 中的 OS X 桌面应用程序中将自定义菜单附加到主视图

How to attach a custom menu to the main view in a OS X desktop app in Swift

给定以下 GitHub 项目:

https://github.com/kellyjanderson/swift-custom-menue

如何link菜单项Custom >> Custom Action,到ViewController中的函数customAction?

AppDelegate

中定义菜单项的出口
@IBOutlet weak var customMenuItem: NSMenuItem!

在你的视图控制器中首先获取 AppDelegate:

的实例
 let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate

获取菜单项的实例,然后将 IBAction 绑定到它:

appDelegate.customMenuItem.action = #selector(customAction(_:))

例如,您想要将操作 customAction 绑定到您的菜单项。可以在viewDidLoad

中添加如下代码
 override func viewDidLoad() {
        super.viewDidLoad()
         let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
         print(appDelegate.customMenuItem)
        appDelegate.customMenuItem.action = #selector(customAction(_:))
    }

然后定义IBAction

 func customAction(sender: NSMenuItem){
        print("Custom Menu Item clicked")
    }

输出:

<NSMenuItem: 0x6080000a0720 Custom Action>
Custom Menu Item clicked

所以链接的问题 很接近,但没有为我提供具体的解决方案。这是我解决这个问题的方法。

首先在 ViewController 中你需要将你的函数标记为 @IBAction

    @IBAction func customAction(sender: NSMenuItem){
        print("Custom Menu Item clicked")
    }

一旦该函数被标记为 IBAction,它将在响应链中可用;所以现在您可以按住 Control 键单击并将菜单项拖动到第一响应者图标和 select 您的函数,在此示例中为 customAction。