2010-07-08 13 views
6

Tengo TableCellViewController para administrar celdas en mi UITableView. Cada celda tiene una etiqueta na UISwitch (dictTypeSwitch). A quiero asignar el método para cambiar eventos para que pueda guardar el estado del botón.Agregue acción personalizada: @selector a UISwitch en TableViewCell

Hasta ahora he hecho esto:

asignar la función de oponerse setstate:

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

para la gestión de eventos:

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

De emisor consigo objeto UISwitch de la que puede obtener estado.

Hasta ahora todo está bien.

Pero si quiero guardar el estado de UISwitch, tengo que obtener rowIndex para esta celda. ¿Cómo puedo lograr esto?

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

Gracias

Respuesta

4

Puede utilizar .tag property de la UISwitch para almacenar un entero arbitrario. Esto se puede establecer en el índice de fila.

Si es posible encontrar la UITableViewCell de los padres del UISwitch, se puede obtener la ruta del índice con

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

Gracias Kenny ... –

Cuestiones relacionadas