简体   繁体   English

Swift Mac OSX NSButton 标题颜色

[英]Swift Mac OSX NSButton title color

I would like to know how to change title color to a NSButton in swift, I've seen lots of examples in objective-c but I think in swift the implementation is different, can anyone provide me an example?我想知道如何在 swift 中将标题颜色更改为 NSButton,我在 objective-c 中看到了很多示例,但我认为在 swift 中,任何人都可以提供不同的示例吗?

try this in viewDidLoad or somewhere. viewDidLoad或其他地方尝试一下。

In Swift 3: 在Swift 3中:

    let pstyle = NSMutableParagraphStyle()
    pstyle.alignment = .center

    button.attributedTitle = NSAttributedString(string: "Title", attributes: [ NSForegroundColorAttributeName : NSColor.red, NSParagraphStyleAttributeName : pstyle ])

Swift 4 斯威夫特4

I've added this as an additional answer since it changes only the requested attribute without overwriting or adding additional ones. 我将其添加为其他答案,因为它仅更改请求的属性,而不会覆盖或添加其他属性。

if let mutableAttributedTitle = button.attributedTitle.mutableCopy() as? NSMutableAttributedString {
    mutableAttributedTitle.addAttribute(.foregroundColor, value: NSColor.white, range: NSRange(location: 0, length: mutableAttributedTitle.length))
    button.attributedTitle = mutableAttributedTitle
}

在Swift4中

button.attributedTitle = NSMutableAttributedString(string: "Hello World", attributes: [NSAttributedStringKey.foregroundColor: NSColor.white, NSAttributedStringKey.paragraphStyle: style, NSAttributedStringKey.font: NSFont.systemFont(ofSize: 18)])

Swift 5 Swift 5

button.contentTintColor = NSColor.white

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM