10

I'd like to have a subclass of NSSegmentedControl where the various segments are different colors. I've tried subclassing NSSegmentedControl and adding the following code:

- (void)drawRect:(NSRect)dirtyRect
{
    NSColor *color = [NSColor redColor];
    [color setFill];
    NSRectFill(dirtyRect);
    [super drawRect:dirtyRect];
}

enter image description here

That looks close except that 1. it colors the whole segmented control the same color, red in this case, and 2. there's a little bit of color bleed over on the edges.

I also tried subclassing NSSegmentedCell and adding this:

- (void)drawSegment:(NSInteger)segment inFrame:(NSRect)frame withView:(NSView *)controlView
{
    NSColor *color;
    switch (segment) {
        case 0:
            color = [NSColor redColor];
            break;
        case 1:
            color = [NSColor blueColor];
            break;
        case 2:
            color = [NSColor greenColor];
            break;
        case 3:
            color = [NSColor orangeColor];
            break;
        default:
            break;
    }
    [color setFill];
    NSRectFill(frame);
    [super drawSegment:segment inFrame:frame withView:controlView];
}

enter image description here

This is better in that the various segments are displaying unique colors, however I would hardly consider this acceptable. I want the entire segment to be filled in with the appropriate color for that segment and it would be nice if it had the gradient and shading as in the first screenshot.

Please let me know how I can achieve this.

Thanks.

Jason Marcell
  • 2,785
  • 5
  • 28
  • 41
  • You're lucking out that the current implementation of segmented control uses translucency in its drawing. This allows the red that you're painting underneath the control to shine through. That could change with any update to Mac OS X. To do this correctly, should make your own NSView subclass that does all of the drawing in drawRect: rather than trying to tint the existing control. – Jon Hess Mar 31 '12 at 01:50
  • Oh, Jon, possibly related to what you're saying, there are actually about a half dozen different styles. I wonder how the other styles might also affect this. – Jason Marcell Mar 31 '12 at 02:46

1 Answers1

6

You need to specify fixed width for segments.

enter image description here

Then your code will work pretty good (Screenshot is from my test project)

enter image description here

And don't forget to disable tint

 [self.segment.cell setControlTint:NSClearControlTint ];
sergeyne
  • 1,268
  • 12
  • 18