2010-07-08 8 views
6

J'ai TableCellViewController pour gérer des cellules dans mon UITableView. Chaque cellule a une étiquette na UISwitch (dictTypeSwitch). A vouloir assigner une méthode pour changer les événements afin que je puisse sauvegarder l'état du bouton.Ajouter une action personnalisée: @selector à UISwitch sur TableViewCell

Jusqu'à présent, je l'ai fait ceci:

assign fonction setState à l'objet:

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

pour la gestion des événements:

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

de l'expéditeur je reçois objet UISwitch dont je peut obtenir l'état.

Jusqu'ici tout va bien. Mais si je veux enregistrer l'état de UISwitch, je dois obtenir rowIndex pour cette cellule. Comment puis-je y parvenir?

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; 
} 

Merci

Répondre

4

Vous pouvez utiliser .tag property de l'UISwitch pour stocker un entier arbitraire. Cela peut être défini sur l'index de ligne.

S'il est possible de trouver le UITableViewCell du parent de UISwitch, vous pourriez obtenir le chemin d'index avec

NSIndexPath* indexPath = [theTableView indexPathForCell:theCell]; 
+0

Merci Kenny ... –