Set background color of NSView and NSImageView in cocoa
Asked Answered
S

4

16

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

Sneed answered 9/6, 2014 at 10:29 Comment(1)
AFAIK there is no other way. You need to subclass view to set background color.Wightman
A
43

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.

Antagonist answered 9/6, 2014 at 11:17 Comment(3)
Can the "Second" (or something similar) be done w/o CGColor? F.e. on system versions, which didn't have CGColor available?Tradescantia
@Tradescantia On which version you are working ? Also you are using Objective-C or Swift ?Antagonist
I target 10.6+ (the lowest allowed by Mother Apple these days) using Obj-C.Tradescantia
S
12

you cannot draw something custom without subclassing NSView however you can change background colour of layer.

[yourView setWantsLayer: YES];
[yourView.layer setBackgroundColor: [NSColor redColor].CGColor];
Shut answered 9/6, 2014 at 11:8 Comment(0)
T
2

You can apply a background color to any NSView descendant via Interface Builder by implementing a category extension like this:

@implementation NSView (backgroundColor)

- (void)setBgColor:(NSColor *)color {
    //
    [self setWantsLayer:YES];
    self.layer = [CALayer layer];
    [self.layer setBackgroundColor:[color CGColor]];
}

@end

and provide a value for it in the User Defined Runtime Attributes panel in IB:

enter image description here

Tarahtaran answered 27/9, 2017 at 15:1 Comment(0)
Y
2

In Swift you can change the NSImageView background color like this:

self.myBackgroundView.wantsLayer = true
self.myBackgroundView.layer?.backgroundColor = NSColor.red.cgColor

if you want an image as background you can use the following:

self.myBackgroundView.wantsLayer = true
let image : NSImage = #imageLiteral(resourceName: "imageResourceName")
self.myBackgroundView.layer?.backgroundColor = NSColor.init(patternImage: image).cgColor
Yangyangtze answered 7/2, 2020 at 16:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.