tableView cellForRowAtIndexPath最初调用多次

时间:2011-07-04 05:26:48

标签: iphone objective-c ios

我试图了解每个单元格的渲染是如何工作的。这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"QuestionCell";
    static NSString *cellNib = @"QuestionsTableViewCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        //cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:cellNib owner:self options:nil];
        cell = [nib objectAtIndex:0];        
        NSLog(@"%@", @"--> load from nib");
    }
    return cell;
}

此代码中的NSLog最初被调用8次(因为我最初有8行可见)。然后,当我开始滚动时,它会被调用一次然后不再调用。我认为它应该被称为一次,因为它应该在第一次调用后重新使用它?为什么在最初的8之后再次调用它? (抓头......)

1 个答案:

答案 0 :(得分:4)

当您滚动表格视图时,屏幕上可能有9个单元格。当你开始时不需要这个,但是当你滚动时,第9个单元格是必需的,因为顶部单元格离开,底部的新单元格进入。细胞不能在一半中重复使用。 :)