Swift Mac OSX NSButton标题颜色

时间:2015-01-10 11:39:22

标签: macos swift xcode6 nsbutton

我想知道如何在swift中将标题颜色更改为NSButton,我在objective-c中看到了很多例子,但我认为在swift中实现方式不同,有人能为我提供一个例子吗?

3 个答案:

答案 0 :(得分:21)

viewDidLoad或其他地方试试。

在Swift 3中:

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

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

答案 1 :(得分:7)

Swift 4

我已将此作为附加答案添加,因为它仅更改所请求的属性而不会覆盖或添加其他属性。

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

答案 2 :(得分:1)

在Swift4中

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