【问题标题】:How can i Popup a NSMenu in a custom views in NSMenuItems?如何在 NSMenuItems 的自定义视图中弹出 NSMenu?
【发布时间】:2018-03-07 18:49:44
【问题描述】:

我有一个带有自定义视图的 NSMenu,就像这样。

ViewController.swift

class ViewController: NSViewController {

    @IBOutlet var theMenu: NSMenu!
    @IBOutlet var theMenuItem: NSMenuItem!
    @IBOutlet var customView: NSView!

    override func viewDidLoad() {
        theMenuItem.view = customView
    }

    @IBAction func showTheMenuWithCustomView(_ sender: NSButton) {
        // Popup the menu below button
        let position = NSPoint(x: 0, y: sender.frame.height+2)
        theMenu.popUp(positioning: nil, at: position, in: sender)
    }

 }

这很好用。

但在自定义视图中,我需要弹出另一个菜单。在我调用 popUp 方法后,它什么也不显示。代码如下:

CustomView.swift

class CustomView: NSView {

    @IBAction func showCustomViewMenu(_ sender: NSButton) {
        // Create the menu in custom view
        let customViewMenu = NSMenu()
        // Add a menu item in it
        customViewMenu.addItem(withTitle: "no one care", action: nil, keyEquivalent: "")
        // Popup the menu below button
        let position = NSPoint(x: 0, y: sender.frame.height+2)
        customViewMenu.popUp(positioning: nil, at: position, in: sender)
    }

 }

你可以克隆这个项目来测试它:

https://github.com/Caldis/NSMenuQuestion

如何在 NSMenuItems 的自定义视图中弹出 NSMenu?

【问题讨论】:

    标签: swift macos popup views nsmenu


    【解决方案1】:

    使用这一行在 CustomView 上显示额外的弹出窗口:

    NSMenu.popUpContextMenu(customViewMenu, with: NSApp.currentEvent!, for: sender)
    

    此外,如果您还需要在整个CustomView 上禁用其他弹出窗口,请在CustomView 中覆盖rightMouseDown,如下所示:

    class CustomView: NSView {
        override func rightMouseDown(with event: NSEvent) {
            // Do nothing
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多