2010-10-27 28 views
95

Quiero tener el índice seleccionado para UITableView. He escrito siguiente código:Obtener índice seleccionado de UITableView

NSIndexPath *index = [NSIndexPath indexPathForRow:1 inSection:0]; 
[tableView scrollToRowAtIndexPath:index 
       atScrollPosition:UITableViewScrollPositionTop 
         animated:YES]; 

Esto siempre trabajar por primera elemento. Quiero tener índice seleccionado en indexPathForRow.

Ayuda por favor. Gracias.

Respuesta

201
NSIndexPath *selectedIndexPath = [tableView indexPathForSelectedRow]; 
+5

Si permite varias selecciones, considere usar: - (NSArray *) indexPathsForSelectedRows – yura

+2

ya no funciona –

+0

@Codecracker Probé el código. Aún funciona. – yuchaozh

4

En didSelectRowAtIndexPath, establezca una interfaz declarada NSIndexPath como la ruta de índice devuelta. Luego puedes desplazarte a esa variable. Si necesita ayuda, coméntela y le daré un código de muestra.

+0

Sí por favor, puesto algunos ejemplos de código – iOSDev

+4

Código de ejemplo: http://pastie.org/1254081 –

+0

Como alternativa, puede utilizar el método de Chris para el uso rápido. El método anterior ofrece más control y puede ser modificado por su controlador de vista detallada (ejemplo). –

5

Usar este código

CGPoint location =[sender locationInView:self.tableView]; 
NSIndexPath *swipedIndexPath = [self.tableView indexPathForRowAtPoint:location]; 
UITableViewCell *swipedCell = [self.tableView cellForRowAtIndexPath:swipedIndexPath]; 
NSIndexPath *indexPath = [self.tableView indexPathForCell:swipedCell]; 
7

Obtener fila seleccionada actual. Puede ser útil si solo tiene una sección.

- (NSUInteger)currentSellectedRowIndex 
{ 
    NSIndexPath *selectedIndexPath = [self.tableView indexPathForSelectedRow]; 
    if (selectedIndexPath) { 
     return selectedIndexPath.row; 
    } 
    else { 
     return NSNotFound; 
    } 
} 
Cuestiones relacionadas