【问题标题】:Scrolling messes up custom cells in UITableView滚动会弄乱 UITableView 中的自定义单元格
【发布时间】:2011-11-29 13:32:14
【问题描述】:

我正在开发一个具有UITableView 和自定义UITableViewCells 的应用程序。单元格包含复选框和 3 个标签。用户可以通过单击复选框来选择多行。当我选择多行并滚动表格视图时,复选标记从复选框中消失。这意味着选定的行将更改为未选定模式。如何解决这个问题?

【问题讨论】:

  • 请发布您的 tableView 代码:cellForRowAtIndexPath:

标签: objective-c ipad uitableview scroll


【解决方案1】:

我认为您的问题可能与单元重用有关。在你的控制器中创建一个NSMutableDictionary(应该是实例变量),然后像这样创建它:

dictionary = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                 [NSNumber numberWithBool:NO], [NSIndexPath indexPathForRow:0 inSection:0],
                 [NSNumber numberWithBool:NO], [NSIndexPath indexPathForRow:1 inSection:0], nil];

对所有行执行此操作,或者如果需要,计算行及其索引,但将其所有对象设置为 [NSNumber numberWithBool:NO

现在,tableView:didSelectRowAtIndexPath:

if ([(NSNumber *)[dictionary objectForKey:indexPath] isEqualToNumber:[NSNumber numberWithBool:NO]) {
    [dictionary setObject:[NSNumber numberWithBool:YES] forKey:indexPath];
    // Do any visual updating necessary
} else {
    [dictionary setObject:[NSNumber numberWithBool:NO] forKey:indexPath];
    // Do any visual updating necessary
}

现在我们有了一种存储单元格是否被选中的方法,更改您的单元格标识符以适用于您的单元格:

NSString *identifier = [[dictionary objectForKey:indexPath] stringValue];
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier] autorelease];
}

// Do any visual updating necessary
return cell;

现在,更新您的自定义单元格类以接受 @"0"@"1" 作为标识符,并根据此输入自动更新它们的选定状态。

【讨论】:

    【解决方案2】:

    我猜这是因为细胞被重复使用了。这意味着 cellForRowAtIndex: 在单元格滚动回视图时被调用。并且复选框默认为未选中模式。将复选框的状态存储在数组中,并按此设置单元格的复选框状态

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多