Search code examples
iosuikitcalayer

UIKit: How to mix several CALayers into one view layer?


I would like to mix several sublayers into only one layer. If I simply assign my modifications to the view layer, it works fine:

testView.layer.cornerRadius = 15.0
testView.layer.shadowColor = UIColor.yellow.withAlphaComponent(1.0).cgColor
testView.layer.shadowOpacity = 1.0
testView.layer.shadowRadius = 24.0
testView.layer.shadowOffset = .zero
testView.backgroundColor = .white

enter image description here

Then, I tried this:

testView.layer.cornerRadius = 15.0
// sl1
let layer1 = CALayer()
layer1.shadowColor = UIColor.yellow.withAlphaComponent(1.0).cgColor
layer1.shadowOpacity = 1.0
layer1.shadowRadius = 24.0
layer1.shadowOffset = .zero
// sl2
let layer2 = CALayer()
layer2.shadowColor = UIColor.red.withAlphaComponent(1.0).cgColor
layer2.shadowOpacity = 1.0
layer2.shadowRadius = 24.0
layer2.shadowOffset = .zero
// sublayers
let layer = CALayer()
testView.layer.sublayers = [layer1, layer2]
testView.backgroundColor = .white

But now here is the result I get

enter image description here

There is now no shadow surrounding the white view. Why is this happening?

Thank you for your help


Solution

  • The chief problem with your code is that none of your layers have any size. Thus for example you see no shadow, because the layer itself is of zero size in the top left corner so there is nothing there to cast any shadow.

    It is your job to give a layer a frame immediately after creating it! Typically this will be the same as the bounds of the superlayer. Keep in mind, however, that unlike views, when a view or superlayer is resized, sublayers are not. Thus the sublayer can cease to "fit" its superlayer properly if you don't take measures to correct that.