PhiceDev
PhiceDev

Reputation: 527

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?

Upvotes: 7

Views: 12560

Answers (5)

Mannam Brahmaiah
Mannam Brahmaiah

Reputation: 2283

@IBOutlet weak var resendOTPButton: NSButton!

var buttonTextColorRef : NSColor = DisplayHexColorCode.whiteColor.asColor
self.resendOTPButton.setButtonTextColor(textColor: buttonTextColorRef)


func setButtonTextColor(textColor color: NSColor) {
    if #available(macOS 10.14, *) {
        self.contentTintColor = color
    } else {
        let newAttributedTitle = NSMutableAttributedString(attributedString: attributedTitle)
        let range = NSRange(location: 0, length: attributedTitle.length)
        newAttributedTitle.addAttributes([
            .foregroundColor: color,
        ], range: range)
        attributedTitle = newAttributedTitle
    }
}

Upvotes: 0

moonmonkey
moonmonkey

Reputation: 135

Swift 5

button.contentTintColor = NSColor.white

Upvotes: 0

Hamer
Hamer

Reputation: 1383

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
}

Upvotes: 11

Bionik6
Bionik6

Reputation: 19

In Swift4

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

Upvotes: 1

bluedome
bluedome

Reputation: 2459

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 ])

Upvotes: 22

Related Questions