如何获取当前正在显示的 tableView 的 indexPath.row?
Posted
技术标签:
【中文标题】如何获取当前正在显示的 tableView 的 indexPath.row?【英文标题】:How to get indexPath.row of tableView which is currently being displayed? 【发布时间】:2011-04-01 05:40:36 【问题描述】:我有一个包含许多值的 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.'
可能出了什么问题?
【问题讨论】:
当前正在显示或当前被用户选中? 我问除非你的单元格太大以至于覆盖整个屏幕,否则会显示多个单元格 根据数据量,没有单元格大小可能很小也可能很大 是数组还是单个 NSIndexPath 对象 您需要从数组中传递 indexPath 对象。检查 indexVis 中的 indexPath 是否正确。 【参考方案1】:您可以使用 tableView indexPathsForVisibleRows
函数,它为所有可见的 UITableViewCell
返回 NSArray
的 NSIndexPath
。从indexPath.row
你可以找到你的数组索引。
NSArray *visible = [tableView indexPathsForVisibleRows];
NSIndexPath *indexpath = (NSIndexPath*)[visible objectAtIndex:0];
indexPath.row
会给你显示的第一个对象的索引。
【讨论】:
谢谢,我会尽快尝试并回复您:) 我应该在哪里写这段代码?在cellForRowAtIndexPath
方法上?
你可以从任何地方调用它..在你想要可见单元格列表的地方调用它..
我滚动到某个位置,然后切换到我的标签栏中的另一个标签,然后再次回到同一个 tableView,然后我希望 tableView 应该显示它在切换之前显示的相同单元格。那么在那种情况下我应该在哪里写代码呢?
在代码的viewWillDisappear中编写上面的代码来获取可见数组的indexpath...然后在viewWillAppear中使用tableView的scrollToRowAtIndexPath函数滚动到你之前保存在数组中的indexpath。 .希望这会有所帮助【参考方案2】:
[self.myTableView visibleCells];
NSArray *anArrayOfIndexPath = [NSArray arrayWithArray:[self.myTableView indexPathsForVisibleRows]];
NSIndexPath *indexPath= [anArrayOfIndexPath lastObject];
希望这会对你有所帮助。
【讨论】:
完全和我正在寻找的东西。谢谢:)【参考方案3】:您可以使用 indexPathsForVisibleRows
返回一个索引路径数组,每个索引路径标识接收器中的可见行。
- (NSArray *)indexPathsForVisibleRows
返回值
一个 NSIndexPath 对象数组,每个对象代表一个行索引和部分索引,它们共同标识表视图中的可见行。如果没有行可见,则返回 nil。
【讨论】:
【参考方案4】:您可以使用:[self.tableView visibleCells]
这将返回一个 nsarray 的 UITableViewCell 对象,每个对象代表接收表格视图中的一个可见单元格。
http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UITableView_Class/Reference/Reference.html
【讨论】:
【参考方案5】:获取当前显示中心的准确索引号:
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)
【讨论】:
以上是关于如何获取当前正在显示的 tableView 的 indexPath.row?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Swift 从 tableview 单元格中获取数据而不显示在标签上?
如何使用 Alamofire 4.0 获取 JSON 字典/数组并将其显示在 tableView Cell 上
我正在尝试使用 NSFetchedResultController 从核心数据中获取对象,但它没有在 tableview 中显示任何数据