2010-07-18 75 views
2

我無法使用圖層託管視圖。如預期(視圖充滿黑色)提供該版本的initWithFrame:作品「想要的Core Animation層」在Interface Builder中選擇:無法顯示圖層託管視圖

- (id)initWithFrame:(NSRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) 
    { 
     [self setWantsLayer:YES]; 
     [[self layer] setBackgroundColor:CGColorGetConstantColor(kCGColorBlack)];  
     [[self layer] setContents:[NSImage imageNamed:NSImageNameBonjour]]; 
    } 
    return self; 
} 

我希望能夠以編程方式配置的看法,所以我想刪除依賴於Interface Builder。以下是旨在實現這一目標的第二個版本。這不起作用。的觀點保持不變顏色與父視圖:

- (id)initWithFrame:(NSRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) 
    { 
     CALayer *rootLayer = [CALayer layer]; //Added this line, 
     [self setLayer:rootLayer]; //and this line only 
     [self setWantsLayer:YES]; 
     [[self layer] setBackgroundColor:CGColorGetConstantColor(kCGColorBlack)];  
     [[self layer] setContents:[NSImage imageNamed:NSImageNameBonjour]]; 
    } 
    return self; 
} 

我從文檔中複製的代碼和搜索,我發現網頁和所有的例子確實做到了這一點,但它不工作!

我在做什麼錯?

回答

1

問題不在於圖層,而是在視圖生命週期中圖層被初始化。

如果在代碼中創建視圖並將其添加到已經繪製到屏幕的窗口,則可以使用initWithFrame:方法創建圖層。然而,如果這個觀點正在從一個國家圖書館變爲現實,這將不會起作用。當從NIB初始化時,將在父窗口完全初始化之前調用initWithFrame:方法,這導致層不顯示。當窗口存儲在NIB中時,可以使用awakeFromNib而不是initWithFrame:來確保圖層被正確初始化。

當然,在可以創建圖層的代碼中有兩點很難看。在上述兩種用例中,viewDidMoveToSuperview被稱爲有用的點。應將檢查添加到viewDidMoveToSuperview以確保圖層僅創建一次。

(心理注 - 如果事情沒有意義,你覺得你需要問的堆棧溢出那就是你需要一些睡眠好兆頭。)

0

你能嘗試調用initWithFrame以下?

[layer setFrame:[self bounds]];