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 have faced the same issue and found many solutions but none of them are perfect.
Finally from above answer of pnavk i got the idea. At there the code is for Xamarin/C# users.
The iOS version could be as below:
Swift 2.3
if rootLayer.sublayers?.count > 0 {
rootLayer.sublayers?.forEach {
if $0.name == "bottomBorderLayer" {
$0.removeFromSuperlayer()
}
}
}
let border = CALayer()
let height = CGFloat(1.0)
border.borderColor = UIColor.blackColor().CGColor
border.borderWidth = height
border.frame = CGRectMake(0, self.frame.size.height - height, self.frame.size.width, self.frame.size.height)
border.name = "bottomBorderLayer"
rootLayer.addSublayer(border)
rootLayer.masksToBounds = true
Objective-C
if (rootLayer.sublayers.count > 0) {
for (CALayer *layer in rootLayer.sublayers) {
if ([layer.name isEqualToString:@"bottomBorderLayer"]) {
[layer removeFromSuperlayer];
}
}
}
CALayer *border = [[CALayer alloc] init];
CGFloat height = 1.0;
border.borderColor = [UIColor blackColor].CGColor;
border.borderWidth = height;
border.frame = CGRectMake(0, self.view.frame.size.height - height, self.view.frame.size.width, self.view.frame.size.height);
border.name = @"bottomBorderLayer";
[rootLayer addSublayer:border];
rootLayer.masksToBounds = TRUE;
The above code will work for bottom border only. You can change the border side as per your requirement.
Here before adding any layer to the controller, I have just run a for loop to check whether any border is already applied or not?
To identify previously added border I use name property of CALayer. And compare that layer before remove from sublayers.
I have tried the same code before using name property, but It creates random crash. But after using name property and comparing name before remove will solve the crash issue.
I hope this will help someone.