У меня есть секционное tableView, которое я хочу, чтобы мой пользователь выбрал один элемент из таблицы. Когда они выбирают элемент, рядом с ним должна появиться галочка (используя UITableViewCellAccessoryCheckmark
). Если они сделали предыдущий выбор, проверку следует удалить из ранее выбранной строки. Вот код, который я использую:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
int newRow = [indexPath row];
int oldRow = [lastIndexPath row];
if (newRow != oldRow || newRow == 0)
{
UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
newCell.accessoryType = UITableViewCellAccessoryCheckmark;
UITableViewCell *oldCell = [tableView cellForRowAtIndexPath: lastIndexPath];
oldCell.accessoryType = UITableViewCellAccessoryNone;
[lastIndexPath release];
lastIndexPath = indexPath;
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
lastIndexPath
объявляется конфиденциально в файле .h
.
Этот код прекрасно работает для небольшого списка, который не разбит на разделы. Но в большой таблице, которая разбита на секции, она ставит случайные галочки в строках других секций. Это почти как если бы cellForRowAtIndexPath
игнорировал раздел в indexPath.
Код также дает сбой, если я выбираю строку, которая больше, чем количество строк в наименьшем разделе.
Вот код для cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *itemSection = [items objectForKey:key];
static NSString *SectionsTableIdentifier = @"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:SectionsTableIdentifier] autorelease];
}
NSArray *rowLabel = [itemSection objectAtIndex:row];
cell.textLabel.text = [rowLabel objectAtIndex:1];
NSString *detText = [rowLabel objectAtIndex:0];
detText = [detText stringByAppendingString:@" $"];
detText = [detText stringByAppendingString:[rowLabel objectAtIndex:2]];
cell.detailTextLabel.text = detText;
return cell;
}