【发布时间】:2012-03-21 07:11:04
【问题描述】:
获取 UITableView 中最顶部部分的标题或索引的最准确方法是什么?我不是指索引 0 处的部分,而是当前在滚动时固定在顶部的部分标题。
【问题讨论】:
标签: ios5 uitableview
获取 UITableView 中最顶部部分的标题或索引的最准确方法是什么?我不是指索引 0 处的部分,而是当前在滚动时固定在顶部的部分标题。
【问题讨论】:
标签: ios5 uitableview
您可以像这样获取屏幕顶部的部分:
NSUInteger sectionNumber = [[tableView indexPathForCell:[[tableView visibleCells] objectAtIndex:0]] section];
但是,这种方法对你来说可能不是最优的,因为当它处于两个标题之间的过渡期时,它会得到一个奇怪的数字。只要您在过渡期间不需要知道该部分,就可以了。 我希望这就是你要找的,
【讨论】:
[tableView visibleCells].count > 0
我认为与其查询 visibleCells,不如通过以下方式查询索引路径:
NSInteger section = [[[self.tableView indexPathsForVisibleRows] firstObject] section];
您可以根据需要在UIScrollViewDelegate 方法之一中使用此代码。
【讨论】:
Swift 版本
使用first(当前固定)或last(最后显示)
if let section:Int = tableView.indexPathsForVisibleRows?.last?.section {
tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: section), atScrollPosition: UITableViewScrollPosition.None, animated: true)
}
【讨论】:
让您的类实现 UIScrollViewDelegate,并实现以下功能。 它将确保您仅在 tableview 停止滚动时检索部分。
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
if (!decelerate)
{
// retrieve section here
section = [[[self.tableview visibleCells] objectAtIndex:0] section];
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
// retrieve section here
section = [[[self.tableview visibleCells] objectAtIndex:0] section];
}
【讨论】:
self.tableView visibleCells 给出了UITableViewCells 而不是IndexPaths。得到 indexPaths 后,我们就可以做 indexPaths[0].section.