rabbitinspace
rabbitinspace

Reputation: 894

Why adding sublayer overlaps subviews?

For example I have a view with UILabel as subview. If at some time I add sublayer with some background color to this view's layer, then this label will disappear. Can someone explain this behavior?

Upvotes: 27

Views: 9859

Answers (2)

denis_lor
denis_lor

Reputation: 6547

What worked for me was to insert the layer at a specific index like this:

view.layer.insertSublayer(backgroundLayer, at: 0)

Upvotes: 5

dan
dan

Reputation: 9825

When you add your UILabel as a subview of your view it is adding your UILabel's layer as a sublayer of your view's layer. So when you add another sublayer to your view's layer it will be on top of your UILabel's layer.

You can either add your background layer before you add the UILabel or do:

Swift

view.layer.insertSublayer(backgroundLayer, below: yourLabel.layer)

Objective C

[view.layer insertSublayer:backgroundLayer below:yourLabel.layer]

and it should put the background behind the label.

Upvotes: 47

Related Questions