Why adding sublayer overlaps subviews?

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

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


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.

Tags:

Ios