我想使用自定义NSColor背景([NSColor colorWithPatternImage:[NSImage imageNamed:@"pattern.png"]]
)设置自定义视图(不是主视图)。我已经尝试制作自定义视图类:
·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
然后在AppDelegate中:
[self.homeView changeColor:[NSColor colorWithPatternImage:[NSImage imageNamed:@"pattern.png"]]];
但没有任何反应,颜色保持不变。怎么了?或者有更简单的方法吗? NSView没有backgroundColor
属性:(
答案 0 :(得分:9)
尝试
[self.homeView setWantsLayer:YES];
self.homeView.layer.backgroundColor = [NSColor redColor].CGColor;
答案 1 :(得分:6)
最好使用从setBackground:
属性获取的已制作的background
方法。因此,请将您的changeColor:
方法替换为:
-(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];
}
要更改视图的颜色,您只需执行以下操作:
self.homeView.background = [NSColor colorWithPatternImage:[NSImage imageNamed:@"pattern.png"]]