In an animation I added a lot of sublayers to a view, with:
[self.view.layer addSublayer:layer1];
[self.view.layer addSublayer:
Swift 5:
You can either remove the layer itself or iterate through them and do the following:
layer.removeAllAnimations()
layer.removeFromSuperlayer()
This worked for me and fixed the crash:
[self.view.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]
I changed the view with my image UImageview
, and the crash is gone.
Swift 4.1
self.view.layer.sublayers?.removeAll()
or if in a UIView sub-class just
layer.sublayers?.removeAll()
Swift 2.0:
for layer: CALayer in self.view.layer.sublayers! {
layer.removeFromSuperlayer()
}
or
self.view.layer.performSelector("removeFromSuperlayer")
For swift5 to remove CAShapeLayer from added view
for layer in self.view.layer.sublayers! {
if layer.isKind(of: CAShapeLayer.self) {
layer.removeFromSuperlayer()
}
}
The sublayers
property of a CALayer
object returns a copy of the array. Setting it no nil does nothing about the sublayers. This however will do:
for (CALayer *layer in self.view.layer.sublayers) {
[layer removeFromSuperlayer];
}
Or, in Swift
self.view.layer.sublayers?.forEach { $0.removeFromSuperlayer() }