UITableView 多对勾选择 [英] UITableView Multiple Checkmark Selection
问题描述
阅读了几个与此相关的问题后,我可以使该功能正常工作.然而,我的列表很长而且可以滚动,所以当我向上和向下滚动时,复选标记的选择到处都是.selectedIndexes 是一个 NSMutableArray
.有什么想法吗?
Having read a couple of the questions asked relating to this, I can get the functionality to work. However my list is long and scrollable, so when I scroll up and down the selection of the checkmarks are all over the place. selectedIndexes is a NSMutableArray
. Any ideas?
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
if ([selectedCell accessoryType] == UITableViewCellAccessoryNone) {
[selectedCell setAccessoryType:UITableViewCellAccessoryCheckmark];
[selectedIndexes addObject:[NSNumber numberWithInt:indexPath.row]];
}
else {
[selectedCell setAccessoryType:UITableViewCellAccessoryNone];
[selectedIndexes removeObject:[NSNumber numberWithInt:indexPath.row]];
}
[tableView deselectRowAtIndexPath:indexPath animated:NO];
}
在我的 cellForRowAtIndexPath:
中,我有以下检查.
In my cellForRowAtIndexPath:
i have the following check.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CustomCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
NSDictionary *dictionary = [natures objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:@"Name"];
NSString *cellValue = [array objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
for (int i = 0; i < selectedIndexes.count; i++) {
NSUInteger num = [[selectedIndexes objectAtIndex:i] intValue];
if (num == indexPath.row) {
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}
else {
[cell setAccessoryType:UITableViewCellAccessoryNone];
}
}
return cell;
}
推荐答案
您需要将您的 cellForRowAtIndexPath
修改为以下内容:
You need to modify your cellForRowAtIndexPath
to be the following:
// Assume cell is not checked -- if it is the loop below will check it.
[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;
}
}
您需要这样做,因为可重复使用的单元格可能设置了复选标记——因此您需要清除它.希望这会有所帮助.
You need to do this because a reusable cell might have the checkmark set -- so you need to clear it. Hope this helps.
顺便说一句,使用 NSSet
可能是一个更优雅的解决方案!
Incidentally, using an NSSet
would probably be a more elegant solution!
这篇关于UITableView 多对勾选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!