Add opacity slider to the color panel for one color well but not others

1.7k Views Asked by At

I'd like to add a opacity slider to the NSColorPanel that is shown for 1 specific NSColorWell. All other color wells should not show the opacity slider.

I know I can set this for the sharedColorPanel like so:

 [[NSColorPanel sharedColorPanel] setShowsAlpha:YES];

But how do I do this when I only want this behavior for a single color well?

I tried adding an IBAction, but this IBAction is not called when you click the color well. (So I can't make any changes before the panel is displayed). It is called when you choose another color in the color panel.

4

There are 4 best solutions below

0
On BEST ANSWER

OK, here's the code that works. Set the colorwell class in IB to AlphaColorWell:**

@implementation AlphaColorWell

- (void)activate:(BOOL)exclusive
{
    [[NSColorPanel sharedColorPanel] setShowsAlpha:YES];
    [super activate:exclusive];
}

- (void)deactivate
{
    [super deactivate];
    [[NSColorPanel sharedColorPanel] setShowsAlpha:NO];
}

@end
2
On

The answer, like dealing with most of AppKit, is to subclass.

@interface AlphaColorPanel : NSColorPanel

@end

@implementation AlphaColorPanel

- (BOOL)showsAlpha {
    return YES;
}

@end

Then go into IB and override the class of the singular color panel you want to show the alpha slider.

1
On

AppKit isn't showing the opacity slider in the panel because it thinks the app doesn't support alpha, which is the default. So rather than subclass, just do this:

func applicationDidFinishLaunching(_ aNotification: Notification) {
    ...
    NSColor.ignoresAlpha = false
    ...
}
0
On
class ANColorWell: NSColorWell {
override func activate(_ exclusive: Bool) {
    NSColorPanel.shared.showsAlpha = true;
    super.activate(exclusive);
}

override func deactivate() {
    NSColorPanel.shared.showsAlpha = false;
    super.deactivate();

}
}

This is the swift4.0 version I tried, which I hope will be useful to you