2

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?

Community
  • 1
  • 1
Aamir
  • 5,324
  • 2
  • 30
  • 47

1 Answers1

1

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.

phaxian
  • 1,058
  • 16
  • 28
IluTov
  • 6,807
  • 6
  • 41
  • 103
  • Thanks. Subclassing `NSSearchFieldCell` instead of `NSSearchField` fixed the problems. – Aamir Nov 05 '12 at 22:12
  • @aam1r, could you post your working code? I'm trying to get something similar to work, but am not having very much luck. – Kyle Nov 26 '12 at 21:16
  • @Zenox: I am sorry but I can't paste snippets of the codebase. What I would suggest though is looking at [BWToolkit](http://www.brandonwalkin.com/bwtoolkit/). It's a library of commonly used UI elements. It is open-source and I had to go through the codebase to see how they were doing their customizations and followed a similar idea. – Aamir Nov 26 '12 at 21:19
  • 1
    @Zenox What's your problem exactly? I'll try to help you out. – IluTov Nov 26 '12 at 22:04
  • I tried it and it didn't work for me. If anybody has working code, post it please. – surfrider May 17 '15 at 14:01