Tagging CALayers in iPhone

2019-04-18 10:12发布

问题:

I am looking for a general way to be able to search for a unique CALayer in a hierarchy without having to remember where the layer is in a hierarchy (and use the sublayer: and superlayer: methods).

I know this is possible with UIViews (which makes flipping views easy) but is it possible for CALayer?

thank you in advance for your help

Peyman

回答1:

You can also use the name property of the CALayer.

[layer setName:@"myKey"];

To look it up,

- (CALayer *)myLayer {

    for (CALayer *layer in [superLayerOfMyLayer sublayers]) {

            if ([[layer name] isEqualToString:LabelLayerName]) {
                return layer;
            }
    }

    return nil;
}


回答2:

Apologize. I was being a dunce. CALayer is a key-value coding compliant container so I can create arbitrary values (including tags) in any instance. To create a tag for instance we do:

[rootLayer setValue:[NSNumber numberWithInt:101] forKey:@"PFtag"];

thank you



回答3:

In Swift you can do this

let layer = CAShapeLayer()
layer.name = "\(index)"

Then to get the layers you can do this

for item in self.layer.sublayers! {
    if item.name == "\(index)" {
        item.removeFromSuperlayer()
        item.removeAllAnimations()
    }
}


回答4:

A modern safe take on this.

Assign a name to the layer:

layer.name = "MyLayer"

Then, filter through all sublayers searching for the name:

layer.sublayers?
    .filter { layer in return layer.name == "MyLayer" }
    .forEach { layer in
        layer.removeFromSuperlayer()
        layer.removeAllAnimations()
}