表视图中的重复单元格

时间:2011-02-16 20:13:49

标签: iphone objective-c ipad uitableview


这是我的cellForRowAtIndexPath

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Maledetta"];
if (cell == nil) {
    UIViewController *c;
    if (!IS_IPAD) c = [[UIViewController alloc] initWithNibName:@"NewsRow" bundle:nil];
    else c = [[UIViewController alloc] initWithNibName:@"NewsRow_ipad" bundle:nil];
    cell = (NewsRowController*)c.view;

    if ([titleArray count] > 0) {
        [(NewsRowController*)cell setCellDataWithName:[titleArray objectAtIndex:indexPath.row]  
                                              andDate:[descArray objectAtIndex:indexPath.row] 
                                                  day:[dayArray objectAtIndex:indexPath.row]
                                                month:[monthArray objectAtIndex:indexPath.row]];
    }
    [c release];
}
return cell;
}

为什么它只显示我的4行,之后重复第一次,然后是第四次,直到十次?

+-----------------------+
| A
+-----------------------+
| B
+-----------------------+
| C
+-----------------------+
| D
+-----------------------+
| A (repeated)
+-----------------------+
| B (repeated)
+-----------------------+
| C (repeated)
+-----------------------+
| D (repeated)
+-----------------------+
| A (repeated)
+-----------------------+
| B (repeated)
+-----------------------+

啊,[titleArray count]等于10kCustomCellID是正确的。

感谢。

2 个答案:

答案 0 :(得分:5)

如果在表格的单元格队列中找不到单元格,则只填充单元格。如果找到,则不会使用indexPath.row的值的内容覆盖它。

请改为尝试:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Maledetta"];
if (cell == nil) {
    UIViewController *c;
    if (!IS_IPAD) c = [[UIViewController alloc] initWithNibName:@"NewsRow" bundle:nil];
    else c = [[UIViewController alloc] initWithNibName:@"NewsRow_ipad" bundle:nil];
    cell = (NewsRowController*)c.view;
    [c release];

 }

 if ([titleArray count] > 0) {
        [(NewsRowController*)cell setCellDataWithName:[titleArray objectAtIndex:indexPath.row]  
                                              andDate:[descArray objectAtIndex:indexPath.row] 
                                                  day:[dayArray objectAtIndex:indexPath.row]
                                                month:[monthArray objectAtIndex:indexPath.row]];
  }
  return cell;
}

另外,检查[titleArray count]可能是多余的。您正在使用它来为此表提供单元格的数量,对吧?如果那是零,它甚至不会到达。

答案 1 :(得分:0)

当您呼叫[tableView dequeueReusableCellWithIdentifier:@"Maledetta"]时,表格视图会在其缓存中查找不再在屏幕上的单元格。它会找到您的单元格并使用它们。在您的单元格上实施-prepareForReuse,然后在else实施中添加-cellForRowAtIndexPath:子句来处理重复使用的单元格。

相关问题