Monday, October 19, 2009

Custom color picker



For some apps I've wanted to have a kind of custom control that allows the user to pick colors for several boxes. Here is a simple implementation of that concept. There is a single view in the window which can be subdivided into boxes. A stepper allows the user to increase the number of boxes (up to a reasonable maximum).



Clicking on a box (when one is not currently selected) highlights it (and colors it white), and brings up a color picker. I found this a cleaner design than having a color well in the window.




I think Apple wouldn't like it, but I prefer that, if the user picks a color, we dismiss the color picker right away. I hate having to click a second time to dismiss it. Also, if the user clicks on the window outside the view containing the boxes, then we deactivate and dismiss the color picker.

In order to get mouseDown events in the contentView, I subclassed NSView. The function acceptsFirstMouse is very useful. It means that if another window is active (e.g. the color picker), then we do not have to click first to activate the window, a single mouse click will come through to us.

I'll talk about the bindings and the box View implementation in another post.


#import <Cocoa/Cocoa.h>

@interface MyTouchableView : NSView {
IBOutlet id myView;
}

@end



#import "MyTouchableView.h"
#import "MyColorView.h"

@implementation MyTouchableView

- (id)initWithFrame:(NSRect)frameRect {
self = [super initWithFrame:frameRect];
if (nil == self) { return nil; }
return self;
}

- (BOOL)acceptsFirstResponder {
return YES;
}

- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent {
return YES;
}

- (IBAction)mouseDown:(NSEvent *)e {
NSLog(@"mouseDown in contentView");
// we've got it taken care of...
//[super mouseDown:e];
[myView mouseDownOutsideView];
}

@end