【问题标题】:How to attach a custom menu to the main view in a OS X desktop app in Swift如何在 Swift 中将自定义菜单附加到 OS X 桌面应用程序的主视图
【发布时间】:2016-07-10 02:12:27
【问题描述】:

鉴于以下 GitHub 项目:

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

如何将菜单项 Custom >> Custom Action 链接到 ViewController 中的函数 customAction?

【问题讨论】:

标签: swift macos cocoa nsviewcontroller


【解决方案1】:

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

【讨论】:

  • 感谢您的出色回答。
【解决方案2】:

所以链接的问题Why can't I connect my menu to my view controller IBAction? 接近但没有为我提供具体的解决方案。这是我解决这个问题的方法。

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 2012-09-11
    相关资源
    最近更新 更多