如何更改/修改NSPopUpButton的显示标题 [英] How do I change/modify the displayed title of an NSPopUpButton

查看:98
本文介绍了如何更改/修改NSPopUpButton的显示标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望NSPopUpButton显示的标题与所选菜单项的标题不同.

I would like an NSPopUpButton to display a different title than the title of the menu item that is selected.

假设我有一个NSPopUpButton,允许用户选择货币列表,我如何才能让收合/关闭按钮仅显示货币缩写,而不显示所选货币的菜单标题(即货币)?

Suppose I have an NSPopUpButton that lets the user pick a list of currencies, how can I have the collapsed/closed button show only the currencies abbreviation instead of the menu title of the selected currency (which is the full name of the currency)?

我想我可以覆盖(c2>的)子类中的draw并自己绘制整个按钮,但是现在我希望使用一种更轻量的方法来重用系统的外观.

I imagine I can override draw in a subclass (of NSPopUpButtonCell) and draw the entire button myself, but I would prefer a more lightweight approach for now that reuses the system's appearance.

菜单项包含有关缩写的必要信息,因此这不是问题的一部分.

The menu items have the necessary information about the abbreviations, so that's not part of the question.

推荐答案

子类NSPopUpButtonCell,覆盖drawTitle(_:withFrame:in:)并使用所需的标题调用super.

Subclass NSPopUpButtonCell, override drawTitle(_:withFrame:in:) and call super with the title you want.

override func drawTitle(_ title: NSAttributedString, withFrame frame: NSRect, in controlView: NSView) -> NSRect {
    var attributedTitle = title
    if let popUpButton = self.controlView as? NSPopUpButton {
        if let object = popUpButton.selectedItem?.representedObject as? Dictionary<String, String> {
            if let shortTitle = object["shortTitle"] {
                attributedTitle = NSAttributedString(string:shortTitle, attributes:title.attributes(at:0, effectiveRange:nil))
            }
        }
    }
    return super.drawTitle(attributedTitle, withFrame:frame, in:controlView)
}

以相同的方式,您可以覆盖NSPopUpButton的子类中的intrinsicContentSize.替换菜单,调用super并将原始菜单放回原处.

In the same way you can override intrinsicContentSize in a subclass of NSPopUpButton. Replace the menu, call super and put the original menu back.

override var intrinsicContentSize: NSSize {
    if let popUpButtonCell = self.cell {
        if let orgMenu = popUpButtonCell.menu {
            let menu = NSMenu(title: "")
            for item in orgMenu.items {
                if let object = item.representedObject as? Dictionary<String, String> {
                    if let shortTitle = object["shortTitle"] {
                        menu.addItem(withTitle: shortTitle, action: nil, keyEquivalent: "")
                    }
                }
            }
            popUpButtonCell.menu = menu
            let size = super.intrinsicContentSize
            popUpButtonCell.menu = orgMenu
            return size
        }
    }
    return super.intrinsicContentSize
}

这篇关于如何更改/修改NSPopUpButton的显示标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆