如何添加子视图在NSMenuItem没有故事板?



我知道有这样的答案,但几乎每个人都在故事板中有他们的菜单栏。我使它纯粹在代码中没有使用。xib文件,所以我不知道如何添加子视图到我的NSMenu项目。我的菜单项显示如下:

func setupMenus() {
// 1
let menu = NSMenu()
let one = NSMenuItem(title: "Toggle", action: #selector(didTapOne) , keyEquivalent: "1")
menu.addItem(one)

let warning = NSMenuItem(title: "INSTRUCTIONS", action: #selector(didTapWarning) , keyEquivalent: "")

menu.addItem(warning)

menu.addItem(NSMenuItem.separator())

menu.addItem(NSMenuItem(title: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
}

applicationDidFinishLaunching中定义如下:

statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
NSApp.hide(nil)
if let button = statusItem.button {
button.image = NSImage(systemSymbolName: "lock.shield", accessibilityDescription: "1")
}

我不确定如何添加子视图到这个。我只是希望添加一行文本(这是灰色的:因为它们是指令)和一个自定义按钮,这两者似乎都可以通过子视图实现,但我不确定如何实现。请记住,我没有使用故事板,因为我正在构建一个菜单栏应用程序。

下面的swift代码将在你的statusBarMenu中创建一个子菜单,并插入一个由NSTextField和一个功能性NSButton创建的复合视图。代码可以在Xcode中运行,通过创建一个swift项目,然后删除AppDelegate中所有预先提供的代码,并复制/粘贴下面的代码。为了避免错误,AppDelegate.swift应该重命名为main.swift。

import Cocoa
class MenuHandler: NSObject {
@objc func beep() {
NSSound.beep()
}
@objc func info() {
NSSound.beep()
}
}
let app = NSApplication.shared
let statusItem = NSStatusBar.system.statusItem(withLength:-1)
statusItem.button!.title = "foobar"
let menu = NSMenu()
let menuHandler = MenuHandler()
let one = NSMenuItem(title: "Toggle", action: #selector(menuHandler.beep) , keyEquivalent: "1")
one.target = menuHandler
menu.addItem(one)

let warning = NSMenuItem(title: "INSTRUCTIONS", action: #selector(menuHandler.beep) , keyEquivalent: "")
warning.target = menuHandler
menu.addItem(warning)
let subMenu = NSMenu()
let info = NSMenuItem()
let infoView = NSView(frame:NSMakeRect(0, 0, 180, 24 ))
let txtFld = NSTextField(frame:NSMakeRect(10, 0, 130, 20 ))
txtFld.backgroundColor = NSColor.clear
txtFld.isEditable = false
txtFld.isBordered = false
txtFld.stringValue = "Bunch of information"
let btn = NSButton(frame:NSMakeRect(140, 0, 24, 24 ))
btn.image = NSImage(named:"myImage.png")
btn.imageScaling = .scaleProportionallyDown
btn.imagePosition = .imageOnly 
btn.target = menuHandler
btn.action = #selector(menuHandler.info)
infoView.addSubview(txtFld)
infoView.addSubview(btn)
info.view = infoView
subMenu.addItem(info)
menu.setSubmenu(subMenu, for: warning)
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
statusItem.menu = menu
app.run()

相关内容

  • 没有找到相关文章

最新更新