Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 271
PhiceDev Avatar asked Jan 10 '15 11:01

PhiceDev


3 Answers

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 ])
like image 107
bluedome Avatar answered Nov 17 '22 02:11

bluedome


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
}
like image 11
Hamer Avatar answered Nov 17 '22 03:11

Hamer


In Swift4

button.attributedTitle = NSMutableAttributedString(string: "Hello World", attributes: [NSAttributedStringKey.foregroundColor: NSColor.white, NSAttributedStringKey.paragraphStyle: style, NSAttributedStringKey.font: NSFont.systemFont(ofSize: 18)])
like image 1
Bionik6 Avatar answered Nov 17 '22 02:11

Bionik6