2

I noticed today, when adding 1 CALayer and 2 subviews to my view, when I run the following code in my UIView instance:

[self.layer.sublayers count]

This returns 3. Does this mean that a subview is also considered a sublayer? If I only wanted the CALayers that I've drawn in my sublayers call, how would i do that?

Calvin
  • 8,697
  • 7
  • 43
  • 51
  • I'm not familiar with the hierarchy used by layers, but I did write a [function to log the hierarchy of views](http://stackoverflow.com/questions/2715534/where-does-a-uialertview-live-while-not-dismissed/2715772#2715772). You could modify this code to log the layer tree. Seeing how the views and layers are nested might help you understand how it works better. – progrmr Jul 15 '10 at 15:11

3 Answers3

3

Yes, each UIView has an underlying CALayer which is added to its superview's layer when the view is added to the superview.

I don't know the ideal way to find only your own layers. Since sublayers is an NSArray (as opposed to an NSSet), it means it's an ordered list, which means you can be sure that the order in which you add views to the superview is the same order they will appear in said array.

Thus, if you add your UIViews first, and then add your own drawn CALayers afterwards, you can probably get your own by accessing the objects starting at index 2 (skipping 0 and 1) in sublayers.

Of course, if you then add or remove views to the superview you'd have to modify this value, so presuming this actually works, you'll want to somehow dynamically generate it.

You can ascertain the index for a layer as you add it, using indexOfObject: on the sublayers property. A safer route might be to simply store this index somewhere in a list and to access the sublayers with indices from that list only.

Kalle
  • 13,186
  • 7
  • 61
  • 76
1

From the CALayer documentation:

delegate

Specifies the receiver’s delegate object.

@property(assign) id delegate

Discussion

In iOS, if the layer is associated with a UIView object, this property must be set to the view that owns the layer.

Availability

Available in OS X v10.5 and later.

Related Sample Code

Community
  • 1
  • 1
1

If I only wanted the CALayers that I've drawn in my sublayers call, how would i do that?

You can do this by making the view that is currently a subview of self into a sibling view by having them both be subviews on a containing view. Then your current self.layer.sublayers would just contain the CALayers you added manually.

One way to think about it is that it is the layer hierarchy, not the view hierarchy which defines the render hierarchy. The view hierarchy is just a wrapper to handle interactivity that UIView adds to its underlying CALayer graphics. Thus, when you add a subview to a view, it simultaneously, though in some sense independently, adds its layer as a sublayer to the view's layer. You could probably override this functionality in a subclass or category on UIView...

Hari Honor
  • 8,677
  • 8
  • 51
  • 54