Активируйте вспомогательное представление ячейки (UISwitch) при вызове didSelectRowAtIndexPath - PullRequest
1 голос
/ 21 февраля 2012

Каждая ячейка моего tableView имеет UISwitch в качестве accessoryView:

UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = mySwitch;
[mySwitch addTarget:self action:@selector(SwitchToggle:) forControlEvents:UIControlEventValueChanged];

Переключатель переключается, когда пользователь касается его, но я также хочу, чтобы он переключался при вызове didSelectRowAtIndexPath (когда пользователь касаетсяэта ячейка).

Я пробовал это (но это не работает):

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{  
    UISwitch *tempSwitch = (UISwitch *)[tableView cellForRowAtIndexPath:indexPath].accessoryView;
    [tempSwitch addTarget:self action:@selector(SwitchToggle:) forControlEvents:UIControlEventValueChanged];

    [tableView deselectRowAtIndexPath:indexPath animated:YES]; // cell selection fadeout animation
}

Спасибо.

1 Ответ

1 голос
/ 21 февраля 2012

Код должен выглядеть так:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{  
    UISwitch *tempSwitch = (UISwitch *)[tableView cellForRowAtIndexPath:indexPath].accessoryView;
    [tempSwitch setOn:!tempSwitch.on animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

Помните, что вы также должны обновить свою модель.

...