2011-09-24 45 views
3

我想用自定义NSColor背景([NSColor colorWithPatternImage:[NSImage imageNamed:@"pattern.png"]])设置自定义视图(不是主视图)。我试着做一个自定义的视图类:设置NSView的背景颜色

.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

这应该是最好的方法:http://stackoverflow.com/questions/2962790/best-way-to-change-the-background-color-for-an-nsview – roman

回答

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"]] 
+0

(1)为什么要检查'background'是'无'?如果是这样,释放'消息将不会做任何事情。 (2)为什么在分配新颜色之前立即将'nil'分配给'background'? –

+0

@PeterHosey修正了,谢谢 – Isabel

+3

NSView没有背景属性,甚至没有废弃的属性......我错过了什么? –

9

尝试

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

请提供一些解释。 – ZeMoon

+0

这是通过继承UIView并调用绘制矩形来更改颜色的最佳解决方案。谢谢, –

+1

这是一个关于NSView(Cocoa)而不是UIView(Cocoa Touch)的问题。而且在UIView中也不是最好的方法。 – Bladebunny