Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change NSButton's background color on highlight

I have an NSButton which I want to have a different background color when it's highlighted than when it's not (transparent on not highlighted, if that makes any difference).

At present, I have the following code

[view setWantsLayer:YES];

NSButton* button = [[NSButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[button setBordered:FALSE];
[(NSButtonCell*)[button cell] setHighlightsBy:NSChangeBackgroundCellMask];

[view addSubview:button];

This will change the background to the default window background color on click. If I remove NSChangeBackgroundCellMask the background goes away.

Is there an easy way I can have a different color for the background, or does this require me to subclass NSButton?

like image 989
cobbal Avatar asked Nov 19 '13 05:11

cobbal


2 Answers

In the end, I solved it by subclassing NSButtonCell and overwriting

- (void) highlight:(BOOL)flag withFrame:(NSRect)cellFrame inView:(NSView*)controlView

to make the changes I wanted (changing controlView.layer.backgroundColor based on flag)

like image 159
cobbal Avatar answered Sep 27 '22 21:09

cobbal


You will need to subclass your NSButton and override its mouseDown: and mouseUp: events, change the color of your NSButton in these events.

like image 26
Neha Avatar answered Sep 27 '22 20:09

Neha