簡體   English   中英

如何獲取當前正在顯示的tableView的indexPath.row?

[英]How to get indexPath.row of tableView which is currently being displayed?

我有一個包含許多值的tableView。

我想獲取當前顯示的表的第一個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.'

可能有什么不對?

您可以使用tableView indexPathsForVisibleRows函數,該函數為所有可見的UITableViewCell返回NSIndexPathNSArray indexPath.row您可以找到您的數組索引。

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

indexPath.row將為您顯示第一個對象的索引。

[self.myTableView visibleCells];

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

NSIndexPath *indexPath= [anArrayOfIndexPath lastObject];

希望這會幫助你。

你可以使用indexPathsForVisibleRows

返回索引路徑數組,每個索引路徑標識接收器中的可見行。

- (NSArray *)indexPathsForVisibleRows

回報價值

一組NSIndexPath對象,每個對象表示行索引和段索引,它們共同標識表視圖中的可見行。 如果沒有可見的行,則返回nil。

你可以使用: [self.tableView visibleCells]

這將返回一個UARableViewCell對象的數組,每個對象代表接收表視圖中的一個可見單元格。

http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UITableView_Class/Reference/Reference.html

獲取當前正在顯示的中心的確切索引號:

 let middleIndex = ((tableView.indexPathsForVisibleRows?.first?.row)! + (tableView.indexPathsForVisibleRows?.last?.row)!)/2

例:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

  let middleIndex = ((tableView.indexPathsForVisibleRows?.first?.row)! + (tableView.indexPathsForVisibleRows?.last?.row)!)/2
  print(middleIndex)

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM