Вы должны передать действительное значение NSIndexPath
на cellForRowAtIndexPath:
.Вы использовали 0, что означает отсутствие indexPath.
Вы должны использовать что-то вроде этого:
UITableViewCell *tvc = [tv cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
НО .Не делай этого. Не сохраняйте состояние в UITableViewCell.
Обновите ваш источник данных, когда коммутатор изменил свое состояние.
Если вы реализовали методы UITableViewDataSource, то правильно, почему ваш tableView повторно использует ячейки.Это означает, что состояние ваших ячеек исчезнет при повторном использовании.
Ваш подход может работать для 6 ячеек.Но он потерпит неудачу для 9 ячеек.
Возможно, он даже потерпит неудачу, если прокрутить первую ячейку за пределами экрана.
Я написал небольшую демонстрацию (если вы не используете ARC, добавьте release
там, где это необходимо), чтобы показать вам, как вам следует это сделать:
- (void)viewDidLoad
{
[super viewDidLoad];
self.dataSource = [NSMutableArray arrayWithCapacity:6];
for (NSInteger i = 0; i < 6; i++) {
[self.dataSource addObject:[NSNumber numberWithBool:YES]];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UISwitch *aSwitch = [[UISwitch alloc] init];
[aSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = aSwitch;
}
UISwitch *aSwitch = (UISwitch *)cell.accessoryView;
aSwitch.on = [[self.dataSource objectAtIndex:indexPath.row] boolValue];
/* configure cell */
return cell;
}
- (IBAction)switchChanged:(UISwitch *)sender
{
// UITableViewCell *cell = (UITableViewCell *)[sender superview];
// NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
CGPoint senderOriginInTableView = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:senderOriginInTableView];
[self.dataSource replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:sender.on]];
}
как видите, не очень сложно не хранить состояние в ячейках: -)