【问题标题】:Repeated cells in table view表格视图中的重复单元格
【发布时间】:2024-05-19 20:05:02
【问题描述】:


这是我的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 行,然后再重复第 4 次直到 10 行???

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

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

谢谢。
一个

【问题讨论】:

  • 我建议逐步使用调试器并一次检查一个值。如果需要,您可以使用“po object”打印出对象的原始详细信息。

标签: iphone objective-c ipad uitableview


【解决方案1】:

只有在表格的单元格队列中找不到单元格时,您才会填充该单元格。如果找到它,您不会用 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] 的检查可能是多余的。您正在使用它来给出该表部分中的单元格数量,对吗?如果那是零,它甚至不会到达这里。

【讨论】:

    【解决方案2】:

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

    【讨论】: