几次滚动后,cellForRowAtIndexPath变慢

时间:2013-07-14 11:22:50

标签: ios objective-c cocoa-touch uitableview

我已将[{1}}子类化,以显示1到70之间的数字。 在每个单元格中,我都会查看中奖号码并查看其背景。问题是,在几次滚动后,tableview变得非常慢,无法使用。我不明白为什么因为我的理解我正在重复细胞。也许是因为我每次都要创建70个UITextField?

请告知

UITableViewCell

1 个答案:

答案 0 :(得分:3)

您的单元格在重用时变慢的原因是,即使重新使用单元格,您也会继续向其添加子视图。每次创建或重用单元格时,都会向其添加70个子视图,但是您永远不会删除子视图。您没有看到重复使用的单元格中的“旧”子视图,因为新添加的子视图位于它们之上,但旧的子视图仍然存在。

在分配单元格时,您需要更改代码以仅创建一次子视图并添加子视图。当单元格被重用时,您应该更改视图中的值,但保持视图本身不变。

实现这一目标的一种方法是为每个tempField提供0到69之间的标记,如下所示:

SubCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];
if (cell == nil) {
    cell = [[SubCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"myCell"];
    for(int i=0;i<7;i++)
    {
        for(int j=0;j<10;j++)
        {
            UITextField *tempField = [[UITextField alloc]initWithFrame:CGRectMake(2+(j*31), 4+(i*28), 30, 27)];
            [tempField setBorderStyle:UITextBorderStyleNone];
            [tempField setOpaque:YES];
            [tempField setTextAlignment:NSTextAlignmentCenter];
            [tempField setTextColor:[UIColor whiteColor]];
            [tempField setUserInteractionEnabled:NO];
            [tempField setTag:10*i+j];
            [cell.contentView addSubview:tempField];
        }
    }
}
for(int i=0;i<7;i++)
{
    for(int j=0;j<10;j++)
    {
        UITextField *tempField = [cell subviewWithTag:10*i+j];
        tempField.text = [NSString stringWithFormat:@"%d",i*10+j+1];
        if([[cell.currentWinningArray objectAtIndex:i*10+j] isEqualToString:@"0"])
        {
           [tempField setBackground:[UIImage imageNamed:@"blue"]];
        }
        else
        {
           [tempField setBackground:[UIImage imageNamed:@"orange"]];
        }
    }
}
return cell;