问题描述
||
大家好,我知道这是一个常见的问题,但请帮助我。我有一个表格视图,其中显示了来自NSArray的数据。我想用UITableViewCellAccessorycheckmark选择多行。但是,当我滚动检查标记消失。每个人都在谈论可重复使用的单元格。我理解这个概念,但是无法解决我的问题。因此,请有人可以给我实现cellForRowAtIndexPath和didSelectRowAtIndexPath方法的方法,谢谢。紧急,我用这个代码
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@\"cell\"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@\"cell\"];
}
cell.textLabel.text = [listData objectAtIndex:indexPath.row];
[cell setAccessoryType:UITableViewCellAccessoryNone];
for (int i = 0; i < selectedindexes.count; i++) {
NSUInteger num = [[selectedindexes objectAtIndex:i] intValue];
if (num == indexPath.row) {
[cell setAccessoryType:UITableViewCellAccessorycheckmark];
// Once we find a match there is no point continuing the loop
break;
}
}
解决方法
如果我正确理解了您的问题,则说明您拥有一个数组,并且每当选择了行时就将索引添加到该数组中。那行不通。
我建议您有一个字典来映射选定的行,
NSMutableDictionary *selectedIndexDict;
用您的didSelectRowAtIndexPath:
方法,
[selectedIndexDict setValue:[NSNumber numberWithBool:YES] forKey:[NSString stringWithFormat:@\"%d\",indexPath.row]];
而且,以您的cellForRowAtIndexPath:
方法,
[cell setAccessoryType:UITableViewCellAccessoryNone];
if ([[selectedIndexDict valueForKey:[NSString stringWithFormat:@\"%d\",indexPath.row]] boolValue]) {
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}