swiftmacoscocoanspopupbutton

NSPopupButton that displays image not text of selected item


I am creating a NSPopUpButton that has multiple NSMenuItems each with an image and a title. The functionality I am trying to create is as such: When the popup is displaying I would like it to behave normally, displaying the title and image, however when the popup is closed I would like the button to show only the image of the selected item. Much like how the Calendars Mac app behaves.

When Closed

When Open

Any help would be greatly appreciated.


Solution

  • All you have to do is to set popupButton.imagePosition = .imageOnly. Here's an example:

    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
    }