Как я могу динамически изменить UISwitch UITableView?

У меня есть UItableView, где каждый UITableViewCell содержит UISwitch. Теперь мой вопрос: когда я нажму на один переключатель, тогда как я могу OFF другие переключатели UITableViewCell

В моем коде я уже сделал вид, и я могу ON/OFF переключатели. Но я хочу OFF все остальные переключатели, кроме моего выбранного переключателя.

Пожалуйста, помогите мне, приведя пример или пример исходного кода.

С наилучшими пожеланиями

Изменить

Мой код:

- (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] autorelease];
        switchview = [[UISwitch alloc] initWithFrame:CGRectZero];
        cell.accessoryView = switchview;
        switchCondition = NO;
        [switchview setOn:NO animated:YES];
        [switchview addTarget:self action:@selector(updateSwitchAtIndexPath:) forControlEvents:UIControlEventValueChanged];
        [switchview release];
    }
    if(switchCondition == YES){
    [switchview setOn:YES animated:YES];
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.contentView.backgroundColor = [UIColor clearColor];
    cell.textLabel.text = [NSString stringWithFormat:@"%@",[cellValueArray objectAtIndex:indexPath.row]];
    return cell;
}

- (void)updateSwitchAtIndexPath:(UISwitch*)sender {
    if(sender.on){
        switchCondition = YES;
        [table reloadData];
    }
}

person Emon    schedule 25.11.2012    source источник


Ответы (1)


Обновите модель данных, используемую источником данных таблицы, затем перезагрузите таблицу (или, по крайней мере, видимые строки). Это приведет к перезагрузке каждой строки, и каждый коммутатор будет обновлен последними данными.

Изменить: вот обновленная версия вашего кода:

Вам нужна переменная экземпляра для отслеживания состояния каждого переключателя. Создайте массив для хранения значений YES и NO. В приведенном ниже коде я предполагаю, что есть переменная экземпляра с именем switchConditions типа NSMutableArray, которая была настроена с NSNumber объектами, представляющими значения YES и NO для каждой строки. Это похоже на ваш cellValueArray. Вам также следует избавиться от переменных экземпляра switchView и switchCondition.

- (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] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        UISwitchView *switch = [[UISwitch alloc] initWithFrame:CGRectZero];
        cell.accessoryView = switch;
        [switchview addTarget:self action:@selector(updateSwitchAtIndexPath:) forControlEvents:UIControlEventValueChanged];
        [switch release];
    }

    UISwitchView *switch = (UISwitchView *)cell.accessoryView;
    switch.tag = indexPath.row; // This only works if you can't insert or delete rows without a call to reloadData
    BOOL switchState = [switchConditions[indexPath.row] boolValue];
    switch.on = switchState; // this shouldn't be animated

    cell.contentView.backgroundColor = [UIColor clearColor];
    cell.textLabel.text = cellValueArray[indexPath.row];

    return cell;
}

- (void)updateSwitchAtIndexPath:(UISwitch*)switch {
    NSInteger row = switch.tag;
    if (switch.on){
        // This switch is on, turn all of the rest off
        for (NSUInteger i = 0; i < switchConditions.count; i++) {
            switchConditions[i] = @NO;
        }
        switchConditions[row] = @YES;
        [self.tableView reloadData];
    } else {
        switchConditions[row] = @YES;
    }
}
person rmaddy    schedule 25.11.2012
comment
спасибо за быстрый ответ. пожалуйста, дайте мне пример, потому что я не могу понять, как я могу это сделать .. - person Emon; 25.11.2012
comment
Покажите свой код (обновите свой вопрос) для cellForRowAtIndexPath:, показывающий, как вы настраиваете переключатель для каждой строки. Также покажите код, который у вас есть для обработки события при изменении значения переключателя. - person rmaddy; 25.11.2012
comment
У меня есть вопрос. Теперь, пожалуйста, проверьте, что я должен сделать. - person Emon; 25.11.2012
comment
Этот код неверен. Вы используете один ивар для переключения и другой для поддержания состояния. Вам нужно отслеживать состояние переключателя для каждой строки. Дайте мне немного, и я обновлю свой ответ обновленным кодом. - person rmaddy; 25.11.2012