2010-08-14 40 views
6

que actualmente tiene un botón definido en una celda y un método para realizar un seguimiento de su acción UITouchDown como se muestra:UITableView Cell - obtener IndexPath.row desde el botón?

- (void) clickedCallSign:(id)sender { 

    int index = [sender tag]; 
    NSLog(@"event triggered %@",index); 

} 

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { 
    //Callsign button 
    UIButton *button; 

    CGRect rect = CGRectMake(TEXT_OFFSET_X, BORDER_WIDTH, LABEL_WIDTH, LABEL_HEIGHT); 
    button = [[UIButton alloc] initWithFrame:rect]; 
    cell.tag=[indexPath row]; 
    button.tag=[indexPath row]; 
    [button addTarget:self action:@selector(clickedCallSign:) forControlEvents:UIControlEventTouchDown]; 
    [button setBackgroundColor:[UIColor redColor]]; 
    [button setTitle:@"hello" forState:UIControlStateNormal]; 
    [cell.contentView addSubview:button]; 
    [button release]; 
} 

Sin embargo, cuando hago clic en una celda en el simulador, el mensaje de la consola de depuración es: "activadas por eventos (null) "y mi aplicación se bloquea poco después.

¿Cómo puedo obtener correctamente el valor de indexPath.row en mi método clickedCallSign?

+0

ver mejor solución para encontrar indexPath del botón pulsado: http://stackoverflow.com/a/16270198/308315 – iwasrobbed

Respuesta

2

En primer lugar, index es un int, por lo que su NSLog debe tener este aspecto (nótese el %d):

NSLog(@"event triggered %d", index); 

(Es posible que esto conduce a un accidente, pero también es probable que algo completamente diferente causa inestabilidad.)

+0

el '% d' hizo el truco de obtener el valor de indexPath.row en clickedCallSign :) la aplicación aún se cuelga ... con este rastro de pila: - [ UIButton setText:]: selector no reconocido enviado a la instancia 0x6877a10 2010-08-13 21: 48: 30.324 RF [8047: 207] *** Ter aplicación de minimización debido a la excepción no detectada 'NSInvalidArgumentException', razón: '- [UIButton setText:]: selector no reconocido enviado a la instancia 0x6877a10' – unicornherder

+0

Probablemente esté exagerando algo en alguna parte. La gestión de memoria en el fragmento de código que muestra se ve bien, por lo que algo en otro lugar es incorrecto. –

+1

en realidad ... encontré la solución que necesitaba aquí: http://developer.apple.com/iphone/library/samplecode/Accessory/Introduction/Intro.html Gracias por la ayuda sin embargo. Realmente lo aprecio. – unicornherder

2

La etiqueta es válida hasta que no tenga ambas secciones y filas. Pruebe otra manera de conseguir la trayectoria del índice:

- (void)tableView:(UITableView*)tableView willDisplayCell:(UITableViewCell*)cell forRowAtIndexPath:(NSIndexPath*)indexPath { 

    //... 

    [button addTarget:self action:@selector(clickedCallSign:withEvent:) forControlEvents:UIControlEventTouchDown]; 

    //... 

} 

// Get the index path of the cell, where the button was pressed 
- (NSIndexPath*)indexPathForEvent:(id)event 
{ 
    NSSet *touches = [event allTouches]; 
    UITouch *touch = [touches anyObject]; 
    CGPoint currentTouchPosition = [touch locationInView:self.tableView]; 
    return [self.tableView indexPathForRowAtPoint:currentTouchPosition]; 
} 

- (IBAction)clickedCallSign:(id)sender withEvent:(UIEvent*)event 
{ 
    NSIndexPath* buttonIndexPath = [self indexPathForEvent:event]; 
} 
2

Si no desea utilizar el campo de etiqueta, tienen el botón de invocar este método:

- (void)tapAccessoryButton:(UIButton *)sender 
{ 
    UIView *parentView = sender.superview; 

    // the loop should take care of any changes in the view heirarchy, whether from 
    // changes we make or apple makes. 
    while (![parentView.class isSubclassOfClass:UITableViewCell.class]) 
     parentView = parentView.superview; 

    if ([parentView.class isSubclassOfClass:UITableViewCell.class]) { 
     UITableViewCell *cell = (UITableViewCell *) parentView; 
     NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 
     [self tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath]; 
    } 
} 
Cuestiones relacionadas