remove all subLayers from a view

前端 未结 9 919
春和景丽
春和景丽 2021-02-01 01:16

In an animation I added a lot of sublayers to a view, with:

[self.view.layer addSublayer:layer1];
[self.view.layer addSublayer:         


        
相关标签:
9条回答
  • 2021-02-01 01:33

    Swift 5:

    You can either remove the layer itself or iterate through them and do the following:

    layer.removeAllAnimations()
    layer.removeFromSuperlayer()
    
    0 讨论(0)
  • 2021-02-01 01:36

    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.

    0 讨论(0)
  • 2021-02-01 01:40

    Swift 4.1

    self.view.layer.sublayers?.removeAll()

    or if in a UIView sub-class just

    layer.sublayers?.removeAll()

    0 讨论(0)
  • 2021-02-01 01:47

    Swift 2.0:

        for layer: CALayer in self.view.layer.sublayers! {
            layer.removeFromSuperlayer()
        }
    

    or

        self.view.layer.performSelector("removeFromSuperlayer")
    
    0 讨论(0)
  • 2021-02-01 01:49

    For swift5 to remove CAShapeLayer from added view

    for layer in self.view.layer.sublayers! {
       if layer.isKind(of: CAShapeLayer.self) {
          layer.removeFromSuperlayer()
       }
    }
    
    0 讨论(0)
  • 2021-02-01 01:50

    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() }
    
    0 讨论(0)
提交回复
热议问题