将UITableView配置为包含选择列表时出现问题

时间:2010-12-01 16:36:56

标签: iphone uitableview

我正在编写一个UITableView来表现为包容性选择列表。我的表格显示正确,允许使用复选框选中多个单元格。我的问题是,当滚动出视图时(单元格复选标记消失),已选择的单元格(单元格右侧有一个复选标记)会松开其选定状态。我希望即使单元格滚动到视图外,也可以保留对表格中单元格的选择。有谁知道是什么原因引起的?

这是我在TableViewController类中的代码:

- (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] autorelease];
}

NSUInteger row = [indexPath row];
cell.textLabel.text = [widgetTitles_glob objectAtIndex:row];
cell.detailTextLabel.text = @"";
cell.textLabel.textColor = [UIColor blackColor]; 
cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
cell.accessoryType = UITableViewCellAccessoryNone; 
return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryNone) {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    // Reflect selection in data model
} else if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
    cell.accessoryType = UITableViewCellAccessoryNone;
    // Reflect deselection in data model
}

}

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

当您正确使用UITableView时,只需要根据需要分配许多UITableViewCell实例以适应屏幕。当您向下滚动一个表格,并且一个单元格从屏幕顶部消失时,它将重新定位到底部。

您的委托方法tableView:cellForRowAtIndexPath:负责设置单元格,无论是创建新单元格还是重新配置循环使用的单元格

正确的做法是使用数组来存储已检查/未检查的值。调用didSelectRowAtIndexPath:时,您将更新单元格和数组。调用tableView:cellForRowAtIndexPath:时,可以根据数组中的值配置单元格。

根据您的评论,您已经在didSelectRowAtIndexPath:中做了正确的事情;您只需在设置单元格实例时使用这些值,因为该单元格可以表示已经检查过的行。检查数组,然后相应地设置cell.accessoryType

答案 1 :(得分:0)

在cellForRowAtIndexPath中:您将accessoryType指定为none,因此每当您滚动时,该委托被调用并将附件类型设置为none。所以你应该改变你的代码。

我曾经遇到过这个问题;我提出了如下解决方案。

如果取消选择从该数组中删除,则将所选indexPath的indexPath.row值存储在数组中(此代码应位于didSelectRowAtIndexPath委托中)。在cellForRowAtIndexPath:方法中,我使用了for循环并检查是否存在indexPath.row,然后将其附件类型更改为选中标记,否则为none。

答案 2 :(得分:0)

感谢您的帮助。事实证明,细胞被重置为UITableViewCellAccessoryNone的原因是由于cellForRowAtindexPath中的以下代码行:

cell.accessoryType = UITableViewCellAccessoryNone; 

删除它已经修复了表格。