我想要一个NSPopUpButton
显示与所选菜单项标题不同的标题。
假设我有一个NSPopUpButton
让用户选择货币列表,如何让折叠/关闭按钮仅显示货币缩写而不是所选货币的菜单标题(这是货币的全名)?
我想我可以重写子类中的绘制(NSPopUpButtonCell
)并自己绘制整个按钮,但我现在更喜欢一种更轻量级的方法,可以重用系统的外观。
菜单项包含有关缩写的必要信息,因此这不是问题的一部分。
子类NSPopUpButtonCell
, 覆盖drawTitle(_:withFrame:in:)
并打电话super
和你想要的标题。
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)
}
以同样的方式你可以覆盖intrinsicContentSize
在一个子类中NSPopUpButton
。更换菜单,调用super
并把原来的菜单放回去。
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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)