Search code examples
cocoacalayer

Can NSView's CALayer can be a sublayer of Other View?


It seems following codes does not work.

WebView *wView = [[WebView alloc] init];
[[wView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]] ];
[wView setWantsLayer:YES];
NSView *v = [[NSView alloc] init];
v.frame = CGRectMake(0, 0, 100, 100);
[v setLayer:wView.layer];
[v setWantsLayer:YES];

What I want to is use other view's layer, for example NSTextField's layer or Webview's layer, as sublayer of other view

can this work?


Solution

  • In your example the WebView is layer-backed and the NSView is layer-hosted. This means that from the perspective of the web view it owns the layer and doesn't expect any thing to interact directly with it. From the perspective of the view, the same layer can be manipulated directly.

    Apple's documentation on this is quite clear,

    Layer-backed

    When using layer-backed views you should never interact directly with the layer. Instead you must use the standard view programming practices.

    Layer-hosted

    When using a layer-hosting view you should not rely on the view for drawing, nor should you add subviews to the layer-hosting view.

    By having this hybrid scheme you are probably setting yourself up for trouble because it conflicts with guidelines! I would try another way of solving your problem.