7

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?

PhiceDev
  • 507
  • 2
  • 6
  • 22

4 Answers4

22

try this in viewDidLoad or somewhere.

In Swift 3:

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

    button.attributedTitle = NSAttributedString(string: "Title", attributes: [ NSForegroundColorAttributeName : NSColor.red, NSParagraphStyleAttributeName : pstyle ])
Ky -
  • 30,724
  • 51
  • 192
  • 308
bluedome
  • 2,449
  • 1
  • 22
  • 17
  • 3
    In Swift 2 you need to change `.CenterTextAlignment` to `.Center` – Sebastian Mar 24 '16 at 10:14
  • 3
    Swift 3 version: `let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .center button.attributedTitle = NSAttributedString(string: "Title", attributes: [NSForegroundColorAttributeName : NSColor.red, NSParagraphStyleAttributeName : paragraphStyle])` – Ricardo Barroso Nov 10 '16 at 15:30
  • 1
    What about vertical alignment? – Ky - Nov 17 '16 at 21:55
11

Swift 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
}
Hamer
  • 1,354
  • 1
  • 21
  • 34
1

In Swift4

button.attributedTitle = NSMutableAttributedString(string: "Hello World", attributes: [NSAttributedStringKey.foregroundColor: NSColor.white, NSAttributedStringKey.paragraphStyle: style, NSAttributedStringKey.font: NSFont.systemFont(ofSize: 18)])
Bionik6
  • 19
  • 3
  • Xcode 9 with swift 4 isn't out yet and isn't GM either so although this might not change I think you are jumping the gun here – Chris Jul 23 '17 at 15:02
0

Swift 5

button.contentTintColor = NSColor.white
moonmonkey
  • 125
  • 9