Clear CALayer

I use CALayer and CATextLayers to lay out the sudoku numbers on the iPhone.

I have a tableView that lists some sudokus. When I click one cell of the table, it shows sudoku in another viewController, which is clicked on the navigation controller.

In my method - (void)viewWillAppear ... I call my method - (void)loadSudoku , which I will show you below.

The problem is that when you look at one sudoku, return to the table view using the back button in the navigation bar, and then click another sudoku. Then the old sudoku still exists, and the new one on top of the old one.

I think I need to clean the old one somehow. Any ideas? I have a background image set via the constructor of a real sudoku grid interface. I do not want to delete this.

The method that draws sudoku is as follows:

 - (void)loadSudoku { mainLayer = [[self view] layer]; [mainLayer setRasterizationScale:[[UIScreen mainScreen] scale]]; int col=0; int row=0; for(NSNumber *nr in [[self sudoku] sudoku]) { if([nr intValue] != 0) { //Print numbers on grid CATextLayer *messageLayer = [CATextLayer layer]; [messageLayer setForegroundColor:[[UIColor blackColor] CGColor]]; [messageLayer setContentsScale:[[UIScreen mainScreen] scale]]; [messageLayer setFrame:CGRectMake(col*36+5, row*42, 30, 30)]; [messageLayer setString:(id)[nr stringValue]]; [mainLayer addSublayer:messageLayer]; } if(col==8) { col=0; row++; }else { col++; } } [mainLayer setShouldRasterize:YES]; } 
+4
source share
1 answer

To remove only text layers, you can do this -

 NSIndexSet *indexSet = [mainLayer.sublayers indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop){ return [obj isMemberOfClass:[CATextLayer class]]; }]; NSArray *textLayers = [mainLayer.sublayers objectsAtIndexes:indexSet]; for (CATextLayer *textLayer in textLayers) { [textLayer removeFromSuperlayer]; } 

In a nutshell, the first operator gets all the indices of the text layers, which are a sublayer for the more root layer. Then in the second expression, we get all these layers in a separate array, and then remove them from our super layer, which is our root layer.

Original answer

Try to do it

 mainLayer.sublayers = nil; 
+8
source

All Articles