Change NSButton's background color on highlight

不羁岁月 提交于 2019-12-07 01:55:27

问题


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?


回答1:


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)




回答2:


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




回答3:


Swift version of Cobbal's answer:

override func highlight(_ flag: Bool, withFrame cellFrame: NSRect, in controlView: NSView) {
        //do nothing, to disable highlight
}


来源:https://stackoverflow.com/questions/20064046/change-nsbuttons-background-color-on-highlight

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!