5

I add the layer to my view:

    [self.layer insertSublayer:_gradient above:_another.layer];

Then it doesn't seem to get removed with this, even if I call needsDisplay on the super layer:

        [_gradient removeFromSuperlayer];

How can I remove it?

kev
  • 7,712
  • 11
  • 30
  • 41
  • `removeFromSuperlayer` works and doesn't need `setNeedsDisplay`. Something else is wrong. Are you sure `_gradient` is still set (non-nil) when you call `removeFroMSuperlayer`? – progrmr Aug 29 '13 at 00:59
  • yes, I have it in a if block of _gradient != nil – kev Aug 29 '13 at 01:12
  • 1
    even so, if _gradient is nil, it won't get removed – progrmr Aug 29 '13 at 01:15
  • Can you edit and share more code to show us what you are doing? This should work. Calling removeFromSuperlayer and then setting the layer to nil in a block of if(_gradient) has alway worked for me in the past. – AdamG Aug 29 '13 at 02:22

2 Answers2

4

I use these and then I check to make sure it's removed:

// assuming there is only 1 gradientLayer this should print 1
print(parentView.layer.sublayers?.count as Any)

parentView.layer.sublayers?.removeAll() // remove everything from the parentView
gradientLayer.removeFromSuperlayer() // just to be safe

// check to see if it's in the parentView or not
if let _ = (parentView.layer.sublayers?.compactMap { $0 as? CAGradientLayer })?.first {

    print("gradientLayer has not been removed")
} else {

    print("yay it's removed")
}

// this should now print nil
print(parentView.layer.sublayers?.count as Any)
Lance Samaria
  • 17,576
  • 18
  • 108
  • 256
3

You can set gradient nil after remove from superlayer.It worked for me.

[gradient removeFromSuperlayer];
 gradient =nil;
Donal
  • 6,082
  • 2
  • 19
  • 30