Reputation: 4136
I have 5 CALayers each one is a property. Say I added 3 of them as subviews. I need to ba able to chk if one of the layers is already added to the layer.
Upvotes: 14
Views: 13015
Reputation: 366
XCode 11 - Swift 5
if view.layer.sublayers == nil {
// add Sublayer
}
Upvotes: 1
Reputation: 19602
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")
}
Upvotes: 3
Reputation: 1918
//to check CALayer Contains Sublayer(shpapelayer/textlayer)
if myShapeLayer.sublayers?.count>0
{
var arr:NSArray? = myShapeLayer.sublayers as NSArray
var i:Int=0
for i in 0..<arr!.count
{
var a: AnyObject = arr!.objectAtIndex(i)
if a.isKindOfClass(CAShapeLayer) || a.isKindOfClass(CATextLayer)
{
if a.isKindOfClass(CAShapeLayer)
{
a = a as! CAShapeLayer
if CGPathContainsPoint(a.path, nil, pointOfCircle, true)
{
NSLog("contains shape layer")
}
else
{
NSLog("not contains shape layer")
}
}
if a.isKindOfClass(CATextLayer)
{
a = a as! CATextLayer
var fr:CGRect = a.frame as CGRect
if CGRectContainsPoint(fr, pointOfCircle)
{
NSLog("contains textlayer")
}
else
{
NSLog("not contains textlayer")
}
}
}
}
}
Upvotes: 0
Reputation: 247
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.
Upvotes: 6
Reputation: 4057
Have you tried the superlayer
property ? It should be nil if your layer isn't added anywhere.
Upvotes: 20