Check if a CALayer is already added as a sublayer

I needed to check to see if a gradientLayer was a subLayer of another view. It was the only layer in there so I didn't have to check for anything else. The answers above didn't work for me.

I came across this answer and even though it was used for a different reason it was an easy way to check if the gradientLayer was a child of another view's layer property (the parentLayer) and it works fine for me:

if let _ = (yourParentView.layer.sublayers?.compactMap { $0 as? CAGradientLayer })?.first {

    print("the gradientLayer IS already a subLayer of this parentView's layer property")
} else {

    print("the gradientLayer IS NOT a subLayer of this parentView's layer property")
}

if (layer.superlayer == parentLayer) {
    ...
} else {
    ...
}

Have you tried the superlayer property ? It should be nil if your layer isn't added anywhere.


view.layer.sublayers gives you an array of the sub layers, to see if your layer was added you can do something like view.layer.sublayers.count and once the layer count reaches what you expect dont add more for ex.

if (view.layer.sublayers.count  < 3) {
//add layer
}else{
// do nothing because the layer has already been added.
}

You can also examine each layer in the sublayer array to better identify the layer you are looking for. Since they are properties you should be able to do a comparison to each of the layers in the array to see if the layer you are looking for has been added.