Check if CALayer is added as a sublevel

I have 5 CALayers, each of which is a property. Say I added 3 of them as subtitles. I need to use chk if one of the layers is already added to the layer.

+9
source share
5 answers

Have you tried the superlayer property? It should be zero if your layer is not added anywhere.

+13
source
 if (layer.superlayer == parentLayer) { ... } else { ... } 
+8
source

view.layer.sublayers gives you an array of sublayers to see if your layer has been added, you can do something like view.layer.sublayers.count, and as soon as the number of layers reaches what you expect, don't 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 a sublevel array to better identify the layer you are looking for. Since they are properties, you should be able to compare with each of the layers in the array to see if the layer you are looking for has been added.

+5
source
  • // check that CALayer contains a 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") } } } } } 
0
source

I needed to check if the gradient layer was a sublevel of another view. It was the only layer there, so I didn't have to check anything. The answers above did not help me.

I came across this answer, and although it was used for a different reason, it was an easy way to check if the GradientLayer is a child of another property of the view layer (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 layer property") } else { print("the gradientLayer IS NOT a subLayer of this parentView layer property") } 
0
source

Source: https://habr.com/ru/post/915086/


All Articles