Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current pinned section of UITableView

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.

like image 700
Bot Avatar asked Mar 02 '12 19:03

Bot


3 Answers

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,

like image 172
Kyle Rosenbluth Avatar answered Nov 17 '22 10:11

Kyle Rosenbluth


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)

  }
like image 33
odemolliens Avatar answered Nov 17 '22 10:11

odemolliens


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.

like image 3
Eric Avatar answered Nov 17 '22 09:11

Eric