Swift: remove layer, without removing UIView in UITableViewCell

calayer, ios, iphone, swift, uiview

Solution

I found the problem. I made a simple mistake. I used `self.layer.sublayers`, but I must use `self.contentView.layer.sublayers` this is my mistake.

When I found that, I was able to fix another issues and use `addLayer:below:`.

So, if you don't see a layer that must be in sublayer of your object, means that you're looking at the wrong place, think where it can be else and you'll find it, like in UITableView you need to work with contentView.

Problem

I have UITableViewCell with `UIView` in it. I made some CABasicAnimation and attach it to new CAShapeLayer, then I add this layer to my super layer in my UITableViewCell: ``` self.layer.addSublayer(myLayer!) ``` All nice except that myLayer (and his animation) showing above my `UIView`. I want that label be below `UIView`. I achieve this by adding my `UIView` layer the same way: ``` self.layer.addSublayer(myViewLayer!) ``` In this case, my `UIView` layer be on the top of the CAShapeLayer with animation. But I have a problem, I need to remove layer of UIView - `myViewLayer` because it violates width of the UIView when scroll. When animation is done, and I need to remove layers, I can remove CAShapeLayer - myLayer without troubles. ``` myLayer?.removeFromSuperlayer() ``` But when I try to do the same with `myViewLayer`, my UIView removed too. But I don't want that, I need my UIView on screen and in my view hierarchy. I don't understand why, if look to `self.layer.sublayers` I see this (before adding layers): ``` [<CALayer: 0x7fd1f0d4fe40>, <CALayer: 0x7fd1f0ddc950>] ``` And after animation done and myLayer is removed: ``` [<CALayer: 0x7fd1f0d4fe40>, <CALayer: 0x7fd1f0ddc950>, <CAGradientLayer: 0x7fd1f0de3660>] ``` As you can see CAGradientLayer is a layer of my UIView. So, I haven't it before I manually add it to sublayers array. How I can remove it, without removing my UIView? OR how can I add myLayer below UIView? EDIT In few words I have this layer hierarchy before animation: ``` [<CALayer: 0x7fd1f0d4fe40> <- (I think this is UITableViewCell layer), <CALayer: 0x7fd1f0ddc950> <- (then, this is UITableViewCell content view layer)] ``` In the same time, I have this view hierarchy: UITableViewCell -> Content View -> UIView I need to add new layer with animation, below UIView (I want that UIView partially cover that new layer with animation). How I can do this? I haven't my UIView layer in the UITableView layer hierarchy, so I can't just add layer with animation using `addLayer:below:` and so on.

Original source