2012-11-25 4 views
0

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

В моем коде я уже сделал вид, и я могут ON/OFF переключатели.But я хочу 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]; 
    } 
} 

ответ

1

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

Edit: Вот обновленная версия кода:

Вам нужна переменная экземпляра для отслеживания состояния каждого коммутатора. Создайте массив для хранения значений 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; 
    } 
} 
+0

благодарит за быстрый ответ. пожалуйста, дайте мне пример, потому что я не могу понять, как я могу это сделать. – Emon

+0

Покажите свой код (обновите свой вопрос) для вашего 'cellForRowAtIndexPath:', показывая, как вы настраиваете переключатель для каждой строки. Также покажите код, который вы используете для обработки события при изменении значения переключателя. – rmaddy

+0

У меня вопрос. Теперь проверьте, что мне нужно сделать. – Emon

Смежные вопросы