Question

I thinks a image is better than a thousand words.

enter image description here

What you see in this picture are NSBox Subclass in a NSViewCollection. I set the fill color to "Selected Menu Item Color" is Interface builder.

Why is the color like that ?

Edit : After reading this SO post, I found out I probably have to set the setPatternPhase. But how/where ?

Was it helpful?

Solution 2

Inspired by Smilin Brian's solution I came up with this :

-(void) drawRect: (NSRect)dirtyRect
{
    [super drawRect:dirtyRect];
    if(mouseOver) {
        [NSGraphicsContext saveGraphicsState];

        CGFloat yOffset = NSMaxY([self convertRect:self.bounds toView:nil]);
        CGFloat xOffset = NSMinX([self convertRect:self.bounds toView:nil]);
        [[NSGraphicsContext currentContext] setPatternPhase:NSMakePoint(xOffset, yOffset)];

        [[NSColor selectedMenuItemColor ] setFill];
        NSRectFill(dirtyRect);
        [NSGraphicsContext restoreGraphicsState];
    }
}

For the moment it just handles mouseOver events and not selection but it's pretty much the same.

Just for the who might need that for a NSBox I used :

- (void)awakeFromNib{
    NSTrackingArea* trackingArea = [[NSTrackingArea alloc] initWithRect:self.bounds
                                                                options: (NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow )
                                                                  owner:self userInfo:nil];
    [self addTrackingArea:trackingArea];
}

and

- (void)mouseEntered:(NSEvent *)theEvent {
    mouseOver = true;
    [self setNeedsDisplayInRect:self.bounds];
    [self needsDisplay];
}

- (void)mouseExited:(NSEvent *)theEvent {
    mouseOver= false;
    [self setNeedsDisplayInRect:self.bounds];

    [self needsDisplay];
}

OTHER TIPS

The "Selected Menu Item Color" pattern is designed to be used on "menu-high" items, and it looks like your NSBox is taller than the pattern is.

That is, you could mess around with the pattern phase origin using code from my answer, but I don't think it will do you any good because the pattern just isn't tall enough for your NSBox.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top