我遇到了图层托管视图的问题。此版本的initWithFrame:
按预期工作(视图填充为黑色),在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;
}
我从文档中复制了代码并搜索了网页,我发现的所有示例都是这样做的,但它不起作用!
我做错了什么?
答案 0 :(得分:1)
问题不在于图层,而是在视图生命周期中初始化图层。
如果视图是在代码中创建的并且被添加到已经绘制到屏幕的窗口中,那么可以使用initWithFrame:
方法来创建图层。但是,如果视图是从NIB初始化的话,这将不起作用。当从NIB初始化时,将在父窗口完全初始化之前调用initWithFrame:
方法,这导致层不显示。当窗口存储在NIB awakeFromNib
中时,可以使用initWithFrame:
来代替viewDidMoveToSuperview
,以确保正确初始化图层。
当然,在代码中有两个点可以创建图层是丑陋的。在上述两个用例中,viewDidMoveToSuperview
被称为有用的点。应将检查添加到{{1}}以确保仅创建一次图层。
(心理记录 - 如果某些事情没有意义,你觉得你需要在Stack Overflow上询问,这是一个好的迹象,你需要睡一觉。)
答案 1 :(得分:0)
您可以尝试在initWithFrame中调用以下内容吗?
[layer setFrame:[self bounds]];