NSPopupButton 显示图像而不是所选项目的文本

NSPopupButton that displays image not text of selected item

我正在创建一个 NSPopUpButton,它有多个 NSMenuItems,每个 NSMenuItems 都有一个图像和一个标题。我试图创建的功能是这样的:当弹出窗口显示时我希望它正常运行,显示标题和图像,但是当弹出窗口关闭时我希望按钮仅显示所选项目的图像.很像日历 Mac 应用程序的行为方式。

如有任何帮助,我们将不胜感激。

您只需设置popupButton.imagePosition = .imageOnly。这是一个例子:

func swatch(size: NSSize, color: NSColor) -> NSImage {
    let image = NSImage(size: size)
    image.lockFocus()
    color.drawSwatch(in: NSMakeRect(0, 0, size.width, size.height))
    image.unlockFocus()

    return image
}

override func viewDidLoad() {
    super.viewDidLoad()

    let homeItem = NSMenuItem(title: "Home", action: nil, keyEquivalent: "")
    let workItem = NSMenuItem(title: "Work", action: nil, keyEquivalent: "")
    let familityItem = NSMenuItem(title: "Family", action: nil, keyEquivalent: "")

    let size = NSSize(width: 12, height: 12)
    homeItem.image = swatch(size: size, color: .blue)
    workItem.image = swatch(size: size, color: .purple)
    familityItem.image = swatch(size: size, color: .orange)

    let menu = NSMenu()
    menu.addItem(homeItem)
    menu.addItem(workItem)
    menu.addItem(familityItem)
    popupButton.menu = menu
    popupButton.imagePosition = .imageOnly
}