Removing all CALayer's sublayers

前端 未结 15 978
说谎
说谎 2020-12-07 20:25

I have trouble with deleting all of layer\'s sublayers. I currently do this manually, but that brings unnecessary clutter. I found many topics about this in google, but no a

15条回答
  •  有刺的猬
    2020-12-07 20:36

    I had to do this in Xamarin/C#. I had a UITableViewCell with some CAShapeLayers for borders. All of the above options (including copying the Array and then removing layers caused a crash). The approach that worked for me:

    When adding the CALayer, I gave it a name:

        var border = new CALayer();
        border.BackgroundColor = color.CGColor;
        border.Frame = new  CGRect(x, y, width, height);
        border.Name = "borderLayerName";
        Layer.AddSublayer(border);
    

    In PrepareForReuse on the UITableViewCell, I created a copy of the SubLayers property and removed anything that matched the name I assigned earlier:

        CALayer[] copy = new CALayer[Layer.Sublayers.Length];
        Layer.Sublayers.CopyTo(copy, 0);
        copy.FirstOrDefault(l => l.Name == "borderLayerName")?.RemoveFromSuperLayer();
    

    No crashes.

    Hope this helps!

提交回复
热议问题