2010-09-05 4 views
1

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

     //NSLog(@"This is what we are looking for %@ %@", checkUsername, checkPassword); 
     // Configure the cell... 
    NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section]; 
    NSArray *array =[dictionary objectForKey:@"Settings"]; 
    NSString * cellValue = [array objectAtIndex:indexPath.row]; 

    static NSString *CellIdentifier = @"Cell"; 
    NSUInteger section = [indexPath section]; 
    NSUInteger row = [indexPath row]; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    cell.accessoryView = nil; 


    if (!cell) { 

     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease]; 
     cell.textLabel.adjustsFontSizeToFitWidth = YES; 
      //switcher.on = [[NSUserDefaults standardUserDefaults]boolForKey:@"Settings"]; 

     if (section == 1) 
     { 

      UISwitch *switchView = [[UISwitch alloc] init]; 
      cell.accessoryView = switchView; 
      [switchView setOn:YES animated:NO]; 
      [switchView setTag:[indexPath row]]; 
      [switchView addTarget:self action:@selector(switchWasChangedFromEnabled:) forControlEvents:UIControlEventValueChanged]; 
       //[self.tableView reloadData]; 
      [switchView release]; 
     } 

    } 
    return cell; 
} 

Может кто-нибудь, пожалуйста, сообщите мне, почему переключатели продолжают перемещаться из указанных ячеек, а также возможное средство.

Джастин Галлахер предложил это:

Это происходит потому, что вы кэширование ваши клетки и повторно использовать их. Иногда ячейка с переключателем повторно используется в другом месте. Попробуйте установить другой идентификатор ячейки с коммутатором.

Но может ли кто-нибудь сказать мне, как я могу установить различный идентификатор для каждой ячейки?

Приветствия,

ISEE

ответ

2

Это происходит потому, что вы кэширование ваши клетки и повторно использовать их. Иногда ячейка с переключателем повторно используется в другом месте. Попробуйте установить другой идентификатор ячейки с коммутатором.

+2

NO .. это не так .. это потому, что UISwitch инициализируется методом cellForRowAtIndexPath. поэтому UISwitch вернется в исходное состояние. объявите переменную switchView в файле .h, а затем инициализируйте ее во время viewDidLoad, а затем добавьте коммутатор в свой аксессуар. Это решит проблему –

0

Я использовал следующий код, представленный here [оригинальный источник], чтобы решить мою проблему. Я вставлял фрагмент кода ниже. Кроме того, эта идея была дана мне Джастином Галлахером. Спасибо.

- (void)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (<indexPath is for cell type "A">) { 
    static NSString *SomeIdentifierA = @"SomeIdentifierA"; 

     // This could be some custom table cell class if appropriate  
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SomeIdentifierA]; 
    if (cell == nil) { 
      cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SomeIdentifierA] autorelease]; 
      // Any other attributes of the cell that will never change for type "A" cells. 
    } 

     if (someCondition) { 
      cell.textColor = <someColor>; 
     } else { 
      cell.textColor = <anotherColor>; 
     } 
     cell.text = <some text>;  
    return cell; 
    } else if (<indexPath is for cell type "B") { 
    static NSString *SomeIdentifierB = @"SomeIdentifierB"; 

     // This could be some custom table cell class if appropriate  
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SomeIdentifierB]; 
    if (cell == nil) { 
      cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SomeIdentifierB] autorelease]; 
      // Any other attributes of the cell that will never change for type "B" cells. 
    } 

     cell.text = <some text>;  
    return cell; 
    } else { 
     return nil; // Oops - should never get here 
Смежные вопросы