NSButton: blue background

311 Views Asked by At

I want to make my NSButton look like Xcode's commit button Xcode commit button

But there doesn't seem to be any way to easily change the background color for a NSButton. You have to change the 'border' to No, then set the button's backgroundColor, and set the 'attributedTitle' for the button to make the textColor white. But when I do this, the results don't look close at all:

enter image description here

The button doesn't have any shadow; the text doesn't look centered; it also doesn't support changing backgroundColor when the button is selected, like the button in Xcode does.

This should surely by easy to replicate, since I believe I've seen similar buttons all over the system.

Here is the NSButton subclass I wrote for this:

override func awakeFromNib() {
    super.awakeFromNib()
    self.wantsLayer = true
    self.isBordered = false //Important
    self.layer?.backgroundColor = backgroundColor.cgColor
    self.layer?.cornerRadius = 6.0
    
    let font = NSFont.systemFont(ofSize: 14, weight: .medium)
    let fontColor = NSColor.white
    
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .center

    self.attributedTitle = NSAttributedString(string: self.title, attributes: [NSAttributedString.Key.foregroundColor : fontColor,
        NSAttributedString.Key.font: font, NSAttributedString.Key.paragraphStyle : paragraphStyle]) // to update text, have to update the attributeString's mutableString property
}

Would love to get pointers for where I'm going wrong with this. I would have thought a regular 'push' button with borders and shadow effect is what I need, but with a blue background, but that doesn't seem straigtforward from what I can see.

Thanks.

1

There are 1 best solutions below

1
Z S On

So found the 'easy' solution I was looking for: there's no need to do any NSButton layer tweaking. You just have to set the key equivalent to the 'return' key!

[self.editButton setKeyEquivalent: @"\r"];

This sets the button background color to blue, and works as I had hoped for. If you want some other background color, I guess you have to customize the button like above.