Swift Mac OSX NSButton标题颜色

Phi*_*Dev 7 macos nsbutton swift xcode6

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

blu*_*ome 22

试试这个viewDidLoad或某个地方.

在Swift 3中:

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

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

  • 在Swift 2中,您需要将`.CenterTextAlignment`更改为`.Center` (3认同)
  • Swift 3版本:`let paragraphStyle = NSMutableParagraphStyle()paragraphStyle.alignment = .center button.attributedTitle = NSAttributedString(string:"Title",attributes:[NSForegroundColorAttributeName:NSColor.red,NSParagraphStyleAttributeName:paragraphStyle])` (3认同)

Ham*_*mer 7

斯威夫特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
}
Run Code Online (Sandbox Code Playgroud)