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
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!