Iphone – Possible to copy CALayer from UIView

core-animationiphone

Here's my setup: I have a CALAyer to which I want to add sublayers. I create these sublayers by setting upa UILabel and then adding the UILables layer to my main layer. Of course this leaves the heavy UILabel object hovering around in the background. Is it possible to get the layer with all its content from a UIView and get rid of the UIView itself?
I already tried this:

UILabel* label;
[...]
[mainLayer addSublayer:[label.layer copy]];
[label release];

But whenever I release the UIView, the content of the layer is also removed. Is this even possible or does the UIView's layer always need the UIView itself to show it's content? I thought of the layer as a kind of canvas, to which the UIView paints. I guess I could be wrong with this assumption 🙂

Best Answer

I can't understand why you wouldn't be able to copy a layer. True a layer is an "integral part" of a UIView. But in the end it is just another object with several properties.

Actually there is a method for CALayer called:

- (id)initWithLayer:(id)layer

But it isn't intended to make a copy of a layer. (You can read Apple's docs for the reasoning why)

CALayer does not conform to NSCopying, so you have two options:

  1. Subclass it and implement "copyWithZone:" (and conform to NSCopying)
  2. Write a method/function that will return a "copy" of a CALayer

Regardless of which way you choose, the question you have to ask is: Which properties of the CALlayer do you want to copy?

Let's say you want to copy just the contents and frame:

CALayer copyLayer = [CALayer layer];

copyLayer.contents = theLayerToBeCopied.contents;
copyLayer.frame = theLayerToBeCopied.frame;

return copyLayer;

You could go through and copy every property of the layer, or just copy the ones you need. Might be a good method to put in a CALayer category.

Related Topic