Layer-hosting NSViews(即您提供CALayer实例并使用setLayer:
进行设置的NSView)可以包含子视图。为什么显然呢?因为在苹果自己的Cocoa Slides样例代码项目中,您可以勾选一个复选框,将AssetCollectionView
从背景图层切换到托管图层:
- (void)setUsesQuartzCompositionBackground:(BOOL)flag {
if (usesQuartzCompositionBackground != flag) {
usesQuartzCompositionBackground = flag;
/* We can display a Quartz Composition in a layer-backed view tree by
substituting our own QCCompositionLayer in place of the default automanaged
layer that AppKit would otherwise create for the view. Eventually, hosting of
QCViews in a layer-backed view subtree may be made more automatic, rendering
this unnecessary. To minimize visual glitches during the transition,
temporarily suspend window updates during the switch, and toggle layer-backed
view rendering temporarily off and back on again while we prepare and set the
layer.
*/
[[self window] disableScreenUpdatesUntilFlush];
[self setWantsLayer:NO];
if (usesQuartzCompositionBackground) {
QCCompositionLayer *qcLayer = [QCCompositionLayer compositionLayerWithFile:[[NSBundle mainBundle] pathForResource:@"Cells" ofType:@"qtz"]];
[self setLayer:qcLayer];
} else {
[self setLayer:nil]; // Discard the QCCompositionLayer we were using, and let AppKit automatically create self's backing layer instead.
}
[self setWantsLayer:YES];
}
}
在同一个
AssetCollectionView
类中,为每个应该显示的图片添加了子视图:- (AssetCollectionViewNode *)insertNodeForAssetAtIndex:(NSUInteger)index {
Asset *asset = [[[self assetCollection] assets] objectAtIndex:index];
AssetCollectionViewNode *node = [[AssetCollectionViewNode alloc] init];
[node setAsset:asset];
[[self animator] addSubview:[node rootView]];
[nodes addObject:node];
return [node autorelease];
}
当我构建并运行应用程序并进行操作时,一切似乎都很好。
然而,在苹果公司的NSView类参考中关于
setWantsLayer:
方法中写道:
这是真的吗?示例代码是否不正确,只是偶然它能工作?还是文档是错误的(我怀疑)?或者因为子视图是通过动画代理添加的,所以没问题?使用层托管视图时,您不应该依赖视图来绘制,也不应该向层托管视图添加子视图。