【问题标题】:UITableView Checklist ProblemUITableView 清单问题
【发布时间】:2010-07-13 19:42:17
【问题描述】:

我有这个奇怪的问题。我正在使用 XCode 制作一个清单程序,并且正在使用 UITableView 和 UITableViewCellAccessoryCheckmark。我可以选择单元格并出现复选标记,但不知何故,我尚未在下面选择的其他单元格也会出现复选标记。有什么想法吗?
这是我的复选标记编码:

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell;
cell = [aTableView cellForRowAtIndexPath: indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark; 

}

不知道有没有影响,不过我也实现了这个方法:

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

static NSString *CellIdentifier = @"CellIdentifier";

// Dequeue or create a cell of the appropriate type.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    cell.accessoryType = UITableViewCellAccessoryNone;
}

// Configure the cell.
if(tableView == Table1){

    switch(indexPath.section){
        case 0:
            cell.textLabel.text = [array1 objectAtIndex:indexPath.row];
            break;
        case 1:
            cell.textLabel.text = [array2 objectAtIndex:indexPath.row];
            break;
        case 2:
            cell.textLabel.text = [array3 objectAtIndex:indexPath.row];
            break;
    }

    //cell.textLabel.text = [NSString stringWithFormat:@"Row %d", indexPath.row];
}
if(tableView == Table2){
    cell.textLabel.text = [array4 objectAtIndex:indexPath.row];
}
return cell;

}

谢谢。

【问题讨论】:

  • 你能分享一下你对tableView:cellForRowAtIndexPath:的实现吗?
  • 我同意 Prairiedogg,让我们看看其余的代码。您可能会重复使用单元格,因此不会重置它们的状态。

标签: iphone objective-c xcode uitableview


【解决方案1】:

每次调用tableView:cellForRowAtIndexPath: 时设置cell.accessoryType。否则,当你重用一个单元格时,你会得到它的附件视图,而不是你所期望的。

所以,是的,您需要跟踪何时通过某种方法选择 NSIndexPaths,而不仅仅是查看 accessoryType。

【讨论】:

  • 对不起,你能举个例子说明我如何重置 cell.accessoryType 吗?您是在告诉我每次调用 tableView:cellForRowAtIndexPath: 时保留所选单元格的列表并相应地显示它们的附件类型吗?
  • 是的,保留所选单元格的列表,或者想出一些其他数据结构来跟踪信息。 Michael 的想法是将字典放入数组中,并带有文本键并选择是我使用过的一种技术。然后在设置单元格标题的同时设置附件类型。您每次都需要设置附件类型,因为您没有为每一行创建一个新单元格 - 您经常重复使用现有的(屏幕外)单元格。并且不要考虑放弃重用现有单元 - 通过限制单元分配可以获得真正的性能提升。
【解决方案2】:

您应该将选中/未选中的信息保留在数据源(数组)中。

我还建议您删除 cell.accessoryType = UITableViewCellAccessoryNone; 行。
此行将仅对少数第一个单元格执行。所有其他单元格将被“重用” - 这意味着将使用旧的(已经启动的)单元格,并且您必须修改这些单元格上显示的详细信息(所有内容都在 cellForRowAtIndexPath 中,就像现在一样)。

此外,您还必须添加类似的行(例如cell.accessoryType = ([[array objectAtIndex:indexPath.row] boolValue] ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;)。

一般来说,我建议您使用一个数组来保存表格的数据,而数组中的每一项都是字典。这样,您将能够保存文本和布尔复选标记(在 NSNumber 内)并在需要时轻松访问它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-17
    • 2016-07-08
    • 2013-04-07
    • 2014-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多