NSButton background transparent after getting focu

2020-07-28 09:57发布

问题:

I have a problem with some borderless NSButtons in a view, on a transparent popover. When the popover is first opened, the buttons look exactly as they should, but when the popover (or the view inside it) gains focus, the background becomes transparent. The first time it is opened, it looks like this (As it should):

But when the popover gains focus, the buttons end up like this: , where the background is transparent and the content beneath the popover is visible.

I already tried the following, which I found scattered around the web:

optionsButton.setButtonType(.MomentaryChangeButton)

optionsButton.cell?.showsFirstResponder = false

let bColor = NSColor(red: 230.0/255.0, green: 230.0/255.0, blue: 230.0/255.0, alpha: 1.0)
(optionsButton.cell as! NSButtonCell).backgroundColor = bColor
optionsButton.layer?.backgroundColor = bColor.CGColor

(optionsButton.cell as! NSButtonCell).showsStateBy = .PushInCellMask
(optionsButton.cell as! NSButtonCell).highlightsBy = .ContentsCellMask

optionsButton is, of course, the one on the right. I tried only using some of the code above, but every variation of this doesn't seem to fix it, unfortunately!

Does anyone have any idea on how to avoid this? And does someone know why the trash-button doesn't have the same problem?

Thanks in advance!

回答1:

The following is tested for NSTextField, but should work for buttons as well.

Set the appearance property of the NSButton to NSAppearanceNameAqua. Because if the button doesn't try to do some weird vibrancy effect, he can't mess things up. The labels still look the same and the strange effect is gone.

My words in code:

self.button.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];


回答2:

Updated: SWIFT 4

The following is tested for NSButton:

NameofButton.appearance = NSAppearance(named: NSAppearance.Name.aqua)