0
votes

i would like to be able to set the background of my views. Currently i try to do it by overriding -(void)drawRect:(NSRect)dirtyRect like suggested here, so my custom view looks like this:

@implementation ViewWithBackgroundColor

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // ...
    }

    return self;
}

- (void)dealloc
{
    [super dealloc];
}

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

    [[NSColor greenColor] setFill];
    NSRectFill(dirtyRect);
}

@end

when i hit build an run the view appears in the default grey background, but when i resize the window the view appears in the desired green color.

does anybody knows what i am missing? I am not sure if it is relevant, but the view is stored in a nib. I already tried to call setNeedsDisplay:YES in awakeFromNib, but it did not help.

thx in advance, Yevgeniy

2

2 Answers

2
votes

There are some issues with your ‑drawRect: method. Firstly, you don't need to (and shouldn't) call super's implementation of ‑drawRect: unless there is a very specific reason to do so. The default implementation of ‑drawRect: does nothing, so in this case it's just a wasted message but you should get out of the habit.

Secondly, when drawing something that covers the whole view, you should normally ignore the dirty rect that's passed in, and draw the background by using [self bounds] as the rect passed to NSRectFill().

If you're linking against the 10.6 SDK or above, you can just set the backgroundColor property of the view instead of drawing the background yourself. Earlier SDKs don't support this property.

-4
votes

Why don't you try setting the backgroundColor property to [NSColor greenColor] at init self.backgroundColor = [NSColor greenColor];