开发者

Setting the background color of an NSView

开发者 https://www.devze.com 2023-04-07 00:36 出处:网络
I want to set a cu开发者_运维问答stom view (not the main one) with a custom NSColor background ([NSColor colorWithPatternImage:[NSImage imageNamed:@\"pattern.png\"]]). I\'ve tried making a custom view

I want to set a cu开发者_运维问答stom view (not the main one) with a custom NSColor background ([NSColor colorWithPatternImage:[NSImage imageNamed:@"pattern.png"]]). I've tried making a custom view class:

.h

#import <AppKit/AppKit.h>

@interface CustomBackground : NSView {
    NSColor *background; 
}
@property(retain) NSColor *background;
@end

.m

#import "CustomBackground.h"

@implementation CustomBackground
@synthesize background;

- (void)drawRect:(NSRect)rect
{
    [background set];
    NSRectFill([self bounds]);
}

- (void)changeColor:(NSColor*) aColor
{
    background = aColor;
    [aColor retain];
}
@end

And then in the AppDelegate:

[self.homeView changeColor:[NSColor colorWithPatternImage:[NSImage imageNamed:@"pattern.png"]]];

But nothing happens, the color remains the same. What's wrong? Or is there an easier way? NSView doesn't have a backgroundColor property :(


Try

[self.homeView setWantsLayer:YES];
self.homeView.layer.backgroundColor = [NSColor redColor].CGColor;


It's best to use the already-made setBackground: method that you get from the background property. So replace your changeColor: method with:

-(void)setBackground:(NSColor *)aColor
{
    if([background isEqual:aColor]) return;
    [background release];
    background = [aColor retain];

    //This is the most crucial thing you're missing: make the view redraw itself
    [self setNeedsDisplay:YES];
}

To change the color of your view, you can simply do:

self.homeView.background = [NSColor colorWithPatternImage:[NSImage imageNamed:@"pattern.png"]]
0

精彩评论

暂无评论...
验证码 换一张
取 消