2011-04-01 92 views
8

我有一個很多值的tableView。如何獲取當前顯示的tableView的indexPath.row?

我想獲得當前正在顯示的表格的第一個indexPath.row值。

我該怎麼做?

我獲得以下錯誤,同時實施krishnabhadra的回答是:在該錯誤出現是

線:

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

錯誤:

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.' 

出了什麼問題?

+0

當前正在顯示或當前由用戶選擇? – Krishnabhadra 2011-04-01 05:43:08

+0

我問過,除非你的單元太大以至於它覆蓋了整個屏幕,在那裏顯示的多個單元格當前正在顯示 – Krishnabhadra 2011-04-01 05:44:12

+0

。 – 2011-04-01 05:44:25

回答

21

可以使用的tableView indexPathsForVisibleRows功能,這對於所有可見UITableViewCell返回NSIndexPathNSArray。從indexPath.row您可以找到您的數組索引。

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

indexPath.row會給你顯示第一個對象的索引。

+0

謝謝,我會盡快嘗試並回復您:) – 2011-04-01 05:51:25

+0

我應該在哪裏寫這段代碼?在'cellForRowAtIndexPath'方法? – 2011-04-01 05:52:48

+0

你可以從任何地方調用它。在你想要的可見單元列表中調用它。 – Krishnabhadra 2011-04-01 05:56:28

2
[self.myTableView visibleCells]; 

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

NSIndexPath *indexPath= [anArrayOfIndexPath lastObject]; 

希望這會幫助你。

+0

完全和正是我所期待的。謝謝你:) – 2015-09-18 08:51:40

3

可以使用indexPathsForVisibleRows

返回的每個識別在所述接收器中的可見行索引路徑的陣列。

- (NSArray *)indexPathsForVisibleRows 

返回值

NSIndexPath對象數組每個代表一個行索引和區段索引一起標識表視圖中可見行。如果沒有行可見,則返回nil。