UITableView Multiple Checkmark Selection
Прочитав пару вопросов, связанных с этим, я могу заставить функциональность работать. Однако мой список длинный и прокручиваемый, поэтому, когда я просматриваю вверх и вниз, выбор галочек повсюду. selectedIndexes - это NSMutableArray
. Любые идеи?
- (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:
у меня есть следующая проверка.
- (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;
}
Ответы
Ответ 1
Вам необходимо изменить cellForRowAtIndexPath
следующим образом:
// 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;
}
}
Вам нужно сделать это, потому что ячейка многократного использования может иметь установленную галочку, поэтому вам нужно ее очистить. Надеюсь, это поможет.
Кстати, использование NSSet
, вероятно, будет более элегантным решением!
Ответ 2
Для множественного выбора вам просто нужно viewDidLoad
self.tableView.allowsMultipleSelection = YES;
и
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *tableViewCell = [tableView cellForRowAtIndexPath:indexPath];
tableViewCell.accessoryView.hidden = NO;
// if you don't use a custom image then tableViewCell.accessoryType = UITableViewCellAccessoryCheckmark;
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *tableViewCell = [tableView cellForRowAtIndexPath:indexPath];
tableViewCell.accessoryView.hidden = YES;
// if you don't use a custom image then tableViewCell.accessoryType = UITableViewCellAccessoryNone;
}
Ответ 3
Нет необходимости поддерживать отдельный массив для хранения выбранных строк.
Используйте собственный метод indexPathsForSelectedRows
для получения выделенного массива indexPath. И просто проверьте arrayContains текущий IndexPath в методе cellForRow, как показано ниже:
NSArray *indexPaths = [tableView indexPathsForSelectedRows];
if ([indexPaths containsObject:indexPath]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
#pragma mark- select/deselect
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[[self.tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryCheckmark];
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
[[self.tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryNone];
}