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

查看:34
本文介绍了如何更改/修改 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)?

我想我可以在子类(NSPopUpButtonCell)中覆盖 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.

推荐答案

Subclass 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天全站免登陆