Question

I have a custom subclass of NSSearchField that I would like to set the background color of.

@interface CustomNSSearchField : NSSearchField
@end

So far, I have tried:

Attempt #1

@implementation CustomNSSearchField

- (void)drawRect:(NSRect)rect
{
    [super drawRect:rect];

    [self setDrawsBackground:YES];
    [self setBackgroundColor:[NSColor redColor]];
}

which resulted in no visual changes at all:

attempt 1

I then followed the suggestions here and also tried:

Attempt #2

- (void)drawRect:(NSRect)rect
{
    [super drawRect:rect];

    [[NSColor redColor] setFill];
    NSRectFill(rect);
}

Which results in this:

attempt 2

How do I set the background color inside the bounds and behind the text of the search field?

Était-ce utile?

La solution

You have to redraw the entire thing. There is no property, to specifically change the background-color of the NSSearchField. Check out this example:

Custom NSSearchField

Edit:

Also what's worth to point out. You should never override the controls drawRect method. You should rather make a subclass of NSSearchFieldCell.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top