Set background color of NSView and NSImageView in cocoa

user2713376 picture user2713376 · Jun 9, 2014 · Viewed 16.7k times · Source

I have a some NSViews % NSImageView that I made in IB, how can I set up a background color for each when the app awakesFromNib?

After google and search here, i found that can be done by creating Custom class of NSView or NSImageView and set color in their drawRect method.

Is their any other way by which i can set background color, and no need to create extra class for View/ImageView.

Thanks

Answer

Surjeet picture Surjeet · Jun 9, 2014

Their are two way to set background color of NSView/NSImageView, which i found.

First: By Subclassing of NSView/NSImageView

- (void)drawRect:(NSRect)aRect
{
    [[NSColor redColor] set];
    NSRectFill([self bounds]);
}

Second:

Don't want to make subclass, as you mentioned in your question. Then

[_backgroundView setWantsLayer:YES];
[_backgroundView.layer setBackgroundColor:[[NSColor redColor] CGColor]]];

Here _backgroundView is the IBOutlet/object of NSView/NSImageView. You just need to access layer of NSView/NSImageView for giving him backgroundcolor without subclassing them.