Can I copy CALayer from a UIView?

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

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

But whenever I release a UIView, the contents of the layer are also deleted. Is this possible, or is the UIView itself always needed for the UIView layer to show its contents? I thought of the layer as the canvas on which the UIView is drawn. I think I could be wrong in this assumption :)

+5
source share
5 answers

I do not understand why you cannot copy the layer. The true layer is an "integral part" of the UIView. But in the end, this is just another object with several properties.

Actually there is a method for CALayer called:

 - (id)initWithLayer:(id)layer 

But it is not intended to create a copy of the layer. (You can read Apple docs for reasons)

CALayer is not NSCopying compliant, so you have two options:

  • Subclass and implementation of "copyWithZone:" (and conform to NSCopying)
  • Write a method / function that will return a "copy" of CALayer

No matter which way you choose, the question you ask is: What CALlayer properties do you want to copy?

Say you want to copy only the content and frame:

 CALayer copyLayer = [CALayer layer]; copyLayer.contents = theLayerToBeCopied.contents; copyLayer.frame = theLayerToBeCopied.frame; return copyLayer; 

You can go through and copy all the properties of the layer or just copy the ones you need. Perhaps this is a good way to include the CALayer category.

+4
source

This is not possible: a layer is a property of UIView. Therefore, when you release UIView, its layer has disappeared. Your idea of ​​thinking of a layer as a canvas is not wrong. But this layer is an integral part of the UIView.

+1
source

UILabel is really not a very complicated control. I suggest you abandon this line of attack and learn how to draw what you want using Quartz in the new CGImage. You can then assign this to the CALayer content property without worrying about all this.

0
source

You can also completely bypass UILabel and create your text using CATextLayer .

0
source

use CAReplicatorLayer, you can fully replicate this layer

0
source

All Articles