для тех, кто хочет более общего подхода и для нескольких выбранных ячеек
Сначала создайте (NSMutableArray *) selectedCells, чтобы отслеживать выбранные ячейки.
Далее реализуем 2 метода делегата
-(void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//add the checkmark to cell when selected
if ([tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryNone){
[tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
}
//once selected add that selected cell to the selectedCells array
[self.selectedCells addObject:@(indexPath.row) ];
}
И
-(void)tableView:(UITableView *)tableView
didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
//set the accessory type back to none
if([tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryCheckmark){
[tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone;
}
//remove the selected cells index from the selectedCells array
[self.selectedCells removeObject:@(indexPath.row) ];
}
Теперь, когда вы выбираете ячейку, добавляется галочка, и этот indexPath.row сохраняется в NSMutableArray. Когда вы отменяете выбор этой ячейки, она удаляет галочку и удаляет ее из массива. Это означает, что массив будет содержать только проверенные ячейки.
Затем мы используем этот массив, чтобы дать ячейке правильный accessoryType в методе cellForRowAtIndexPath. Этот метод вызывается каждый раз, когда tableView требует ячейку, мы говорим, что для продажи требуется наличие checkMark при создании или нет.
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
//Create an NSNumber to hold the row of the cell to be created
NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:indexPath.row];
//then ask the array if the selectedCells array has that object.
//if it does then that cell needs a checkmark when created.
if ([self.selectedCells containsObject:rowNsNum]){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else { cell.accessoryType = UITableViewCellAccessoryNone;
}
[cell.textLabel setText:@"your contents"];
}
return cell;
}