2011-04-01 2 views
8

J'ai un tableView avec beaucoup de valeurs.Comment obtenir indexPath.row de tableView qui est actuellement affiché?

Je veux obtenir la première valeur indexPath.row de la table qui est actuellement affichée.

Comment puis-je faire cela?

Je reçois la suite Erreur lors de la mise en œuvre de la réponse de krishnabhadra:

ligne à laquelle l'erreur vient est:

[self.table scrollToRowAtIndexPath:indexVis atScrollPosition:UITableViewScrollPositionTop animated:YES]; 

ERREUR:

Assertion failure in -[NSIndexPath row], /SourceCache/UIKit_Sim/UIKit-1447.6.4/UITableViewSupport.m:2018 
2011-04-01 11:57:25.458 GlossaryPro[1525:207] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid index path for use with UITableView. Index paths passed to table view must contain exactly two indices specifying the section and row. Please use the category on NSIndexPath in UITableView.h if possible.' 

Quoi de mal?

+0

actuellement affiché ou actuellement sélectionné par l'utilisateur? – Krishnabhadra

+0

J'ai demandé à moins que votre cellule ne soit si grande afin qu'elle couvre tout l'écran, plus d'une cellule est affichée – Krishnabhadra

+0

en cours d'affichage. –

Répondre

21

Vous pouvez utiliser la fonction tableView indexPathsForVisibleRows, qui retourne un NSArray de NSIndexPath pour tous UITableViewCell visibles. De indexPath.row vous pouvez trouver votre index de tableau.

NSArray *visible  = [tableView indexPathsForVisibleRows]; 
NSIndexPath *indexpath = (NSIndexPath*)[visible objectAtIndex:0]; 

indexPath.row vous donnera l'index de premier objet affiché.

+0

Merci, je vais essayer bientôt et revenir à vous :) –

+0

Où dois-je écrire ce code? Sur la méthode 'cellForRowAtIndexPath'? –

+0

vous pouvez l'appeler de n'importe où..Appelez-le où vous voulez la liste des cellules visibles .. – Krishnabhadra

2
[self.myTableView visibleCells]; 

NSArray *anArrayOfIndexPath = [NSArray arrayWithArray:[self.myTableView indexPathsForVisibleRows]]; 

NSIndexPath *indexPath= [anArrayOfIndexPath lastObject]; 

Espérons que cela vous aidera.

+0

exactement ce que je cherchais. Merci :) –

3

vous pouvez utiliser indexPathsForVisibleRows

Renvoie un tableau de chemins d'index identifiant chacun une ligne visible dans le récepteur.

- (NSArray *)indexPathsForVisibleRows 

Valeur de retour

Un tableau de NSIndexPath objets représentant chacun un indice de ligne et l'indice de section qui identifient ensemble une ligne visible dans la vue de la table. Retourne zéro si aucune ligne n'est visible.

Questions connexes