2010-01-09 9 views
116

¿Cómo seleccionar una fila mediante programación UITableView modo queSeleccione la fila tableview programación

- (void)tableView:(UITableView *)tableView 
     didSelectRowAtIndexPath:(NSIndexPath *)indexPath 

es ejecutado? selectRowAtIndexPath solo resaltará la fila.

+0

Me encontré con el mismo problema y acabo de corregir el enlace: http://stackoverflow.com/questions/5324501/select-tableviews-row-from-an-another-view Espero que sea útil para usted. – michael

Respuesta

103

De reference documentation:

llamada a este método no causa el delegado para recibir un mensaje tableView:willSelectRowAtIndexPath: o tableView:didSelectRowAtIndexPath:, ni enviar notificaciones a los observadores UITableViewSelectionDidChangeNotification.

Lo que yo haría es:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    [self doSomethingWithRowAtIndexPath:indexPath]; 
} 

Y luego, desde donde se quería llamar selectRowAtIndexPath, que en lugar de llamar doSomethingWithRowAtIndexPath. Además de eso, también puede llamar selectRowAtIndexPath si desea que se produzca la retroalimentación de UI.

+3

O cuando selecciona la fila programáticamente, puede llamar a tableView: didSelectRowAtIndexPath: usted mismo (en la clase que ha conectado como delegado). –

+2

Este método me parece un truco, hizo el trabajo pero creo que debería haber una mejor manera de hacerlo. –

+1

Realmente no creo que necesite crear una llamada "doSomethingWithRowAtIndexPath" ¿no puede simplemente llamar al método de delegado y pasar los argumentos que necesita para ejecutar la lógica didSelect desde el lugar donde implementó el método de delegado? – ImpactZero

63

UITableView selectRowAtIndexPath:animated:scrollPosition: debería hacer el truco.

Simplemente pase UITableViewScrollPositionNone para scrollPosition y el usuario no verá ningún movimiento.


También debe ser capaz de ejecutar manualmente la acción:

[theTableView.delegate tableView:theTableView didSelectRowAtIndexPath:indexPath]

después selectRowAtIndexPath:animated:scrollPosition: por lo que el punto culminante sucede así como cualquier lógica asociada.

+0

Lo siento, eso es lo que estoy usando. Accidentalmente puse scrollToRowAtIndexPath. He actualizado la pregunta. scrollToRowAtIndexPath solo resalta la celda. – 4thSpace

+2

Sí, lo siento. Dice que no disparará didSelectRowAtIndexPath allí en el enlace de documentos que publiqué. Necesito aprender a leer – anq

+0

@anq: ¡Muchas gracias! Me ayuda cuando llamo a didSelectRowAtIndexPath: indexPath en la celda personalizada. – Bentley

2

Utilice esta categoría para seleccionar una fila de la tabla y ejecutar una secuencia determinada después de un retraso.
Llame a este método dentro de su viewDidAppear:

[tableViewController delayedSelection:withSegueIdentifier:] 


@implementation UITableViewController (TLUtils) 

-(void)delayedSelection:(NSIndexPath *)idxPath withSegueIdentifier:(NSString *)segueID { 
    if (!idxPath) idxPath = [NSIndexPath indexPathForRow:0 inSection:0];                                         
    [self performSelector:@selector(selectIndexPath:) withObject:@{@"NSIndexPath": idxPath, @"UIStoryboardSegue": segueID } afterDelay:0];                        
} 

-(void)selectIndexPath:(NSDictionary *)args { 
    NSIndexPath *idxPath = args[@"NSIndexPath"];                                               
    [self.tableView selectRowAtIndexPath:idxPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];                                

    if ([self.tableView.delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)]) 
     [self.tableView.delegate tableView:self.tableView didSelectRowAtIndexPath:idxPath];                                    

    [self performSegueWithIdentifier:args[@"UIStoryboardSegue"] sender:self];                                        
} 

@end 
+2

La pregunta no tiene nada que ver con los segues. –

+0

Sí, nada en su respuesta está relacionado con la pregunta – dulgan

+2

. Valora esta respuesta. Esto funciona perfectamente si el usuario quiere lograr el mismo comportamiento pero está usando storyboards. –

88

Como Jaanus dijo:

Al llamar a este (-selectRowAtIndexPath: animada: Método scrollPosition :) no causa el delegado para recibir una tableView : willSelectRowAtIndexPath: o tableView: didSelectRowAtIndexPath: message, ni enviará UITableViewSelectionDidChangeNotification notificaciones a los observadores.

Así que solo tiene que llamar al método delegate usted mismo.

Por ejemplo:

Swift 3 version:

let indexPath = IndexPath(row: 0, section: 0); 
self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.none) 
self.tableView(self.tableView, didSelectRowAt: indexPath) 

ObjectiveC versión:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0]; 
[self.tableView selectRowAtIndexPath:indexPath 
          animated:YES 
         scrollPosition:UITableViewScrollPositionNone]; 
[self tableView:self.tableView didSelectRowAtIndexPath:indexPath]; 

Swift 2.3 Versión:

let indexPath = NSIndexPath(forRow: 0, inSection: 0); 
self.tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.None) 
self.tableView(self.tableView, didSelectRowAtIndexPath: indexPath) 
+3

Genial, gracias! +1 – edzio27

+1

¡Gracias, amigo! Buena persona – Felipe

2

Hay dos métodos diferentes para plataformas iPad y iPhone, por lo que necesita para poner en práctica tanto:

  • manejador de selección y
  • segue.

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
    [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone]; 
    
    // Selection handler (for horizontal iPad) 
    [self tableView:self.tableView didSelectRowAtIndexPath:indexPath]; 
    
    // Segue (for iPhone and vertical iPad) 
    [self performSegueWithIdentifier:"showDetail" sender:self]; 
    
19

si desea seleccionar alguna fila Esto le ayudará a

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
[someTableView selectRowAtIndexPath:indexPath 
          animated:NO 
        scrollPosition:UITableViewScrollPositionNone]; 

Esto también resaltada la fila. Entonces delegar

[someTableView.delegate someTableView didSelectRowAtIndexPath:indexPath]; 
6

Swift 3.0 Solución

Seleccionar fila

let indexPath = IndexPath(row: 0, section: 0) 
tblView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom) 
myTableView.delegate?.tableView!(myTableView, didSelectRowAt: indexPath) 

DeSelect Fila

let deselectIndexPath = IndexPath(row: 7, section: 0) 
tblView.deselectRow(at: deselectIndexPath, animated: true) 
tblView.delegate?.tableView!(tblView, didDeselectRowAt: indexPath) 
Cuestiones relacionadas