2011-09-24 220 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