我想在UITableview中实现多行选择。但是当我选择带有复选标记的多行并向下滚动时,当我回到选定的行部分时,复选标记消失了。您能否请任何人给我适合我的解决方案。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"SimpleTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
if([_selectedstatearray containsObject:indexPath]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
cell.textLabel.text = [statearray objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = cell.textLabel.text;
NSLog(@"cellText>>%@",cellText);
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
[_selectedstatearray removeObject:cellText];
cell.accessoryType = UITableViewCellAccessoryNone;
} else {
[_selectedstatearray addObject:cellText];
cell.accessoryType=UITableViewCellAccessoryCheckmark;
}
NSLog(@"selectedarray>>%@",_selectedstatearray);
NSString *greeting = [_selectedstatearray componentsJoinedByString:@","];
NSLog(@"%@",greeting);
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
最佳答案
问题出在这段代码中:
if([_selectedstatearray containsObject:indexPath]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
在将_selectedstatearray存储为NSString
indexPath
时,正在检查_selectedstatearray是否包含指定的[_selectedstatearray addObject:cellText];
将上面的代码替换为:
NSString *text = [statearray objectAtIndex:indexPath.row];
if([_selectedstatearray containsObject:text]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}