【问题标题】:Show NSMenu next to NSButton in Swift macOS在 Swift macOS 中的 NSButton 旁边显示 NSMenu
【发布时间】:2016-04-11 21:33:46
【问题描述】:

点击按钮后如何在NSButton 旁边显示NSMenu

这是我目前所拥有的:

@IBOutlet weak var BtnMenu: NSButton!

// Menu
let appMenu = NSMenu()
let showPrefsMenuItem = NSMenuItem(title: "Preferences...", action: #selector(VC.showPrefs(_:)), keyEquivalent: "")
let showAboutMenuItem = NSMenuItem(title: "About", action: #selector(VC.showAbout(_:)), keyEquivalent: "")
let quitAppMenuItem = NSMenuItem(title: "Quit", action: #selector(VC.quitApp(_:)), keyEquivalent: "")

override func viewDidLoad() {
    super.viewDidLoad()

    // Set up menu
    self.appMenu.addItem(self.showPrefsMenuItem)
    self.appMenu.addItem(self.showAboutMenuItem)
    self.appMenu.addItem(NSMenuItem.separatorItem())
    self.appMenu.addItem(self.quitAppMenuItem)
}

// Shows the app menu
@IBAction func openMenu(sender: NSButton) {
    self.appMenu.popUpMenuPositioningItem(self.appMenu.itemAtIndex(0), atLocation: NSEvent.mouseLocation(), inView: nil)
}

但是现在,菜单显示在鼠标位置。有没有办法在按钮旁边显示菜单?

谢谢。

【问题讨论】:

标签: swift macos cocoa


【解决方案1】:

我就是这样解决的:

let p = NSPoint(x: sender.frame.origin.x, y: sender.frame.origin.y - (sender.frame.height / 2))
self.appMenu.popUp(positioning: nil, at: p, in: sender.superview)

在这种情况下,菜单显示在单击的按钮下方。

【讨论】:

    【解决方案2】:

    斯威夫特 3.

    在按钮下显示 NSMenu:

        let p = NSPoint(x: 0, y: sender.frame.height)
        appMenu.popUp(positioning: nil, at: p, in: sender)
    

    在按钮右侧显示 NSMenu:

        let p = NSPoint(x: sender.frame.width, y: 0)
        appMenu.popUp(positioning: nil, at: p, in: sender)
    

    【讨论】:

      【解决方案3】:

      这里只缺少传递发送者的按钮。

      来自 john elemans 的回复:

       let p = NSPoint(x: sender.frame.origin.x, y: sender.frame.origin.y)
       self.appMenu.popUpMenuPositioningItem(self.appMenu.itemAtIndex(0), atLocation:p , inView: sender)
      

      【讨论】:

        【解决方案4】:

        试试这个:

        let p = NSPoint(x: sender.frame.origin.x, y: sender.frame.origin.y)
        self.appMenu.popUpMenuPositioningItem(self.appMenu.itemAtIndex(0), atLocation:p , inView: nil)
        

        【讨论】:

        • 没有。 atLocation 需要 NSPoint,但 sender.frame 是 NSRect,所以它不起作用
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-23
        • 2012-03-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多