Zeist
Zeist

Reputation: 645

how to set background color of NSButton OSX

I want to set the background color of NSButton.There was nothing in the attribute inspector so i was wondering if there was any way to do it programmatically?

Upvotes: 6

Views: 16120

Answers (5)

Ely
Ely

Reputation: 9141

When using macOS 11 or newer, you can set the bezelColor property when using a button with bezelStyle set to .rounded or regularSquare in code, or button style set to 'Push' or 'Bezel' when using interface designer.

let button = NSButton()
button.title = "Example"
button.bezelStyle = .rounded // or .regularSquare
button.bezelColor = .controlAccentColor

Upvotes: 0

user4657588
user4657588

Reputation:

Use the background layer of the NSButton like so:

buttonName.layer.backgroundColor = NSColor.redColor.CGColor;

Upvotes: 4

uchuugaka
uchuugaka

Reputation: 12782

I would recommend against cell subclassing. Cells are deprecated and on the way out.

NSButton does allow you to set an image without a bezel.

Subclassing NSView or NSControl, doing custom drawing and tracking states of mouse events and application active/window active to draw all the custom states is as effective if not better.

Cells don't know about AutoLayout so you should be careful if go to cell land.

Upvotes: 5

Sheen Vempeny
Sheen Vempeny

Reputation: 826

Other than subclassing you can use layer approach like this

NSButton *button = [[NSButton alloc] initWithFrame:frame];
[superView addSubView:button];
[button setWantsLayer:YES];
button.layer.backgroundColor = [NSColor blueColor].CGColor;

or you can make an image with that specified color and apply that image to the Button.

Upvotes: 6

Cristik
Cristik

Reputation: 32904

System controls will need to follow the Apple look&feel, so you cannot easily change the background colour. If you want to accomplish this, you'll need to subclass NSButton and overwrite the drawRect: method. The downside is that you'll also need to handle the text drawing, and possibly different rendering based on button state.

Edit. Actually, you'll need to subclass the NSButtonCell class for the drawing stuff, more info can be found here: https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSButtonCell_Class/index.html#//apple_ref/doc/uid/20000093-SW15

Upvotes: 6

Related Questions