The main animation preview is sometimes not displayed
I am working on a Cocoa project using Core Animation and I have a custom view that is displayed in two windows. It always appears in one window, but sometimes does not appear in another window when the application starts. As far as I can tell, this is completely coincidental. Here is the code I am calling when the view is initialized. It gets this code whether the view is displayed.
[self setWantsLayer:YES];
root = [self layer]; // root is a CALayer
root.layoutManager = [CAConstraintLayoutManager layoutManager];
root.autoresizingMask = kCALayerWidthSizable | kCALayerHeightSizable;
[root setBackgroundColor:CGColorGetConstantColor(kCGColorBlack)];
[self setNeedsDisplay:YES];
Why would the view appear sometimes and other times?
EDIT: Does it make a difference if I create my own CALayer on my own, instead of setting it to the view "layer" as I am currently doing?
a source to share
It looks like there was a pretty simple solution, but it wasn't well documented. Instead of setting root to the subclass level, I create root as a new CALayer and then set it to root as the layer. The original question code now looks like this:
// self is the sub-classed NSView
[self setWantsLayer:YES];
// Set root to a new CALayer
root = [CALayer layer];
root.layoutManager = [CAConstraintLayoutManager layoutManager];
root.autoresizingMask = kCALayerWidthSizable | kCALayerHeightSizable;
[root setBackgroundColor:CGColorGetConstantColor(kCGColorBlack)];
// Set the view layer to root
[self setLayer:root];
I think that sometimes when my initialization code was called, the view did not initialize its associated layer, so root did not get properly assigned. This is just a guess, but making the above changes fixes my problem where the view is not always displayed.
a source to share
When you say that it is displayed in two windows, do you mean that there are two instances of the view class that are in two windows, or do you mean that you tried to put the same actual instance of the view in two windows? A given view can only be part of one view hierarchy. Setting it to one will remove it from the hierarchy it was in.
a source to share