Reputation: 11855
What is the most accurate way to get the title or index of the top most section in the UITableView? I don't mean the section at index 0, but the section header that is currently pinned at the top while scrolling.
Upvotes: 9
Views: 5127
Reputation: 2641
Swift version
Use first (current pinned) or last (last displayed)
if let section:Int = tableView.indexPathsForVisibleRows?.last?.section {
tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: section), atScrollPosition: UITableViewScrollPosition.None, animated: true)
}
Upvotes: 2
Reputation: 3363
i believe that instead of querying for the visibleCells, it's better to ask for the index paths the following way:
NSInteger section = [[[self.tableView indexPathsForVisibleRows] firstObject] section];
You can use this code in one of the UIScrollViewDelegate
methods according to your needs.
Upvotes: 3
Reputation: 1682
You can get the section at the top of the screen like so:
NSUInteger sectionNumber = [[tableView indexPathForCell:[[tableView visibleCells] objectAtIndex:0]] section];
But, this method might not be optimal for you because it will get the number will weird when it is in the transition period between two headers. As long as you don't need to know the section during the transition you should be fine. I hope this is what your looking for,
Upvotes: 14
Reputation: 1107
Have your class implement the UIScrollViewDelegate, and implement the following functions. It will ensure you retrieve section only when tableview stops scrolling.
- (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];
}
Upvotes: -1