开发者

Subviews counted in root CALayer's sublayers?

开发者 https://www.devze.com 2023-01-07 02:01 出处:网络
I noticed today, when adding 1 CALayer and 2 subviews to my view, when I run the following code in my UIVi开发者_开发百科ew instance:

I noticed today, when adding 1 CALayer and 2 subviews to my view, when I run the following code in my UIVi开发者_开发百科ew 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?


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.


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...


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

0

精彩评论

暂无评论...
验证码 换一张
取 消