简体   繁体   English

清除 CALayer

[英]Clear a CALayer

I use a CALayer and CATextLayers to lay out the numbers on a sudoku grid on the iPhone.我使用CALayerCATextLayers在 iPhone 上的数独网格上布置数字。

I have a tableView that lists some sudokus.我有一个列出一些数独的 tableView。 When I tap one table cell it shows the sudoku in another viewController that is pushed on to the navigation controller.当我点击一个表格单元格时,它会在另一个视图控制器中显示数独,该视图控制器被推送到导航 controller。

In my - (void)viewWillAppear ... method I call my - (void)loadSudoku method which I will show you below.在我的- (void)viewWillAppear ... 方法中,我调用了我的- (void)loadSudoku方法,我将在下面向您展示。

The problem is when you look at one sudoku, go back to the table view using the "back" button in the navigationBar and then tap another sudoku.问题是当您查看一个数独时,go 使用导航栏中的“返回”按钮返回表格视图,然后点击另一个数独。 Then the old sudoku is still there, and the new one is drawn on top of the old one.然后旧数独还在,新数独在旧数独之上绘制。

I guess I need to clear the old one somehow.我想我需要以某种方式清除旧的。 Any ideas?有任何想法吗? I do have a background image set through the interface builder of the actual sudoku grid.我确实通过实际数独网格的界面生成器设置了背景图像。 I don't want to remove this.我不想删除这个。

The method that draws the sudoku looks like this:绘制数独的方法如下所示:

- (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];
}

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 statement gets all the indices of text layers which are a sublayer to over root layer.简而言之,第一条语句获取作为根层子层的文本层的所有索引。 Then in the second statement we get all those layers in a separate array and then we remove them from their superlayer which is our root layer.然后在第二个语句中,我们将所有这些层放在一个单独的数组中,然后我们将它们从它们的超级层中移除,也就是我们的根层。

Original Answer原始答案

Try doing this,尝试这样做,

mainLayer.sublayers = nil;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM