How to add a background image to an NSView

Unlike UIView, NSView does not have a background property – which makes it less obvious how to set either a colour or a background image to your bland grey windows.

Here’s how to do it:

First, create a subclass of NSView and assign it to the view you’d like to change in interface builder. When you create your class Xcode provides two methods for you, one of which is drawRect:dirtyRect. In it you can specify a colour and fill the view with it before calling super:

- (void)drawRect:(NSRect)dirtyRect
{
    // add a background colour
    [[NSColor whiteColor] setFill];
    NSRectFill(dirtyRect);
    
    [super drawRect:dirtyRect];
}

Now instead of a bland grey you’ll have a shining white.

If a solid colour isn’t what you’re after, create your own colorWithPatternImage and use that instead – therefore adding a background image to your NSView:

- (void)drawRect:(NSRect)dirtyRect
{
    // add a background image
    NSColor *backgroundColor = [NSColor colorWithPatternImage:[NSImage imageNamed:@"Background"]];
    [backgroundColor setFill];
    NSRectFill(dirtyRect);
    
    [super drawRect:dirtyRect];
}




Leave a Reply