Добавить пользовательское действие: @selector в UISwitch на TableViewCell

У меня есть TableCellViewController для управления ячейками в моем UITableView. Каждая ячейка имеет метку на UISwitch (dictTypeSwitch). Я хочу назначить метод для переключения событий, чтобы я мог сохранить состояние кнопки.

До сих пор я сделал это:

назначить функцию setState объекту:

[cell.dictTypeSwitch addTarget:self action:@selector(setState:) forControlEvents:UIControlEventTouchUpInside];

функция обработки события:

- (void)setState:(id)sender {
    BOOL state = [sender isOn];
    NSString *rez = state == YES ? @"YES" : @"NO";
    NSLog(rez);
}

От отправителя я получаю объект UISwitch, из которого я могу получить состояние.

Пока все в порядке.

Но если я хочу сохранить состояние UISwitch, я должен получить rowIndex для этой ячейки. Как я могу этого добиться?

The cells are made inside function cellForRowAtIndexPath. Se the code bellow:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"DictionariesTableCellViewController";
    DictionariesTableCellViewController *cell = (DictionariesTableCellViewController *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];


        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"DictionariesTableCellViewController" owner:nil options:nil];

        for (id currentObject in topLevelObjects) {
            if ([currentObject isKindOfClass:[UITableViewCell class]]) {
                cell = (DictionariesTableCellViewController *) currentObject;
                break;
            }
        }
    }

    // Configure the cell...

    cell.dictTypeLabel.text = [NSString stringWithFormat:@"row - %i",indexPath.row];
    [cell.dictTypeSwitch addTarget:self action:@selector(setState:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

Спасибо


person Borut Tomazin    schedule 08.07.2010    source источник


Ответы (1)


Вы можете использовать .tag свойство для хранения произвольного целого числа. Это может быть установлено в индекс строки.

Если возможно найти UITableViewCell из родителя UISwitch, вы можете получить путь к индексу с помощью

NSIndexPath* indexPath = [theTableView indexPathForCell:theCell];
person kennytm    schedule 08.07.2010