NSPopUpButton 子类 attributedTitle

NSPopUpButton subclass attributedTitle

我对如何子类化 NSPopUpButton 感到困惑,即我无法在按钮上设置 attributedTitle(以获取自定义字体、颜色和基线偏移量)。

以下代码无效:

class CustomPopUpButton: NSPopUpButton {
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        self.wantsLayer = true
        self.layerContentsRedrawPolicy = .OnSetNeedsDisplay

        self.attributedTitle = NSAttributedString(string: self.title, attributes: [
            NSFontAttributeName: NSFont(name: "Impact", size: 15)!,
            NSForegroundColorAttributeName: NSColor(calibratedRed: 0.2, green: 0.270588235, blue: 0.031372549, alpha: 1),
            NSBaselineOffsetAttributeName: 2
        ])
    }
}

查看 documentation 时,您会发现 NSPopUpButton 仅适用于字符串。

attributedTitle 属性 仅引用其超类 NSButton,因此不由 NSPopUpButton 本身表示。 但是,要设置标准标题,您可以使用 setTitle 方法。

来自文档:

If the receiver displays a pop-up menu, this method changes the current item to be the item with the specified title, adding a new item by that name if one does not already exist.

NSPopUpButton 显示选定的菜单项。当您设置菜单项的属性字符串时,弹出按钮将显示一个属性标题。

正如@Willeke 所指出的,我需要在菜单项本身上设置属性字符串。我只想将它设置在按钮上,让菜单项不以相同的字体显示,但我决定接受它。

我在初始化时循环遍历菜单中的项目并为每个项目设置样式,然后在添加项目后重新设置。

这是我的带有 NSAttributedStringNSPopUpButton 子类的最终代码:

class CustomPopUpButton: NSPopUpButton {
    required init?(coder: NSCoder) {
        super.init(coder: coder)

        setItemStyles()
    }

    override func addItemsWithTitles(itemTitles: [String]) {
        super.addItemsWithTitles(itemTitles)

        setItemStyles()
    }

    private func setItemStyles() {
        for item in self.itemArray {
            item.attributedTitle = NSAttributedString(string: item.title, attributes: [
                NSFontAttributeName: NSFont(name: "Impact", size: 15)!,
                NSForegroundColorAttributeName: NSColor(calibratedRed: 0.2, green: 0.270588235, blue: 0.031372549, alpha: 1),
                NSBaselineOffsetAttributeName: 2
            ])
        }
    }
}