托管层的 NSView(因此您提供 CALayer 实例并设置它的 NSView setLayer:
)显然可以包含子视图。为什么很明显?因为在 Apple 自己的Cocoa Slides 示例代码项目中,您可以选中一个复选框,将其AssetCollectionView
从 layer-backed 切换为 layer-hosting:
- (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];
}
当我构建并运行应用程序并使用它时,一切似乎都很好。
但是,在Apple 的 NSView 类参考中,setWantsLayer:
它读取的方法是:
使用图层托管视图时,您不应依赖视图进行绘图,也不应将子视图添加到图层托管视图。
什么是真的?示例代码是否不正确,它的工作原理只是巧合?或者文件是假的(我怀疑)?还是因为子视图是通过动画代理添加的?