0

我的表格视图中有 9 行,并且只想将按钮添加到第 1 行和第 2 行。当代码第一次运行时,它会在 1 和 2 上显示按钮。但是当我滚动表格视图时,它开始随机显示第 4,5 行,8,9。代码如下。请指教我做错了什么。

- (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView
                         dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
            initWithStyle:UITableViewCellStyleDefault
            reuseIdentifier:CellIdentifier];
    }

    cell.textLabel.text = [NSString stringWithFormat:@"Row %d",[indexPath row]];            
    if([indexPath row] == 0 || [indexPath row] == 1)
    {
        cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    }
    return cell;
}
4

1 回答 1

3

这是一个常见的错误。当您只需要某些单元格中的内容时,您需要重置其他单元格中的值。

if([indexPath row] == 0 || [indexPath row] == 1) {
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
} else {
    cell.accessoryType = UITableViewCellAccessoryNone;
}

基本上,对于任何给定的单元格标识符,您需要为每个索引路径设置相同的属性集。如果您只为某些索引路径设置属性,那么随着单元格被重用,您将开始看到问题。

于 2013-09-10T01:30:03.993 回答