如何通过 Interface Builder 设置 NSButton 的文本颜色?

Tro*_*roy 5 xcode interface-builder nsbutton

关于如何以编程方式设置文本颜色有几个问题。这一切都很好,但也必须有一种方法可以通过 Interface Builder 做到这一点。

“显示字体”框可用于更改按钮文本的大小,但 Xcode 会忽略使用该小部件所做的任何颜色更改,并且 NSButton 的属性检查器没有颜色选择器...

Rya*_*oni 5

我不知道为什么 NSButton 仍然缺少这个。但这是 Swift 4 中的替换类:

import Cocoa

class TextButton: NSButton {
    @IBInspectable open var textColor: NSColor = NSColor.black
    @IBInspectable open var textSize: CGFloat = 10

    public override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
    }

    public required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func awakeFromNib() {
        let titleParagraphStyle = NSMutableParagraphStyle()
        titleParagraphStyle.alignment = alignment

        let attributes: [NSAttributedStringKey : Any] = [.foregroundColor: textColor, .font: NSFont.systemFont(ofSize: textSize), .paragraphStyle: titleParagraphStyle]
        self.attributedTitle = NSMutableAttributedString(string: self.title, attributes: attributes)
    }
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

在此处输入图片说明


twe*_*doh -4

编辑:误读问题。以下是更改 iOS 应用程序上按钮文本的方法。

只是为了澄清,这对你不起作用?

  • 添加按钮
  • 单击它并转到属性检查器
  • 更改“文本颜色”字段中的颜色

将按钮颜色更改为红色