How to get a UITableView's visible sections?

Or the really easy way would be to take advantage of valueForKeyPath and the NSSet class:

NSSet *visibleSections = [NSSet setWithArray:[[self.tableView indexPathsForVisibleRows] valueForKey:@"section"]];

Basically you get an array of the section values in the visible rows and then populate a set with this to remove duplicates.


Swift version

if let visibleRows = tableView.indexPathsForVisibleRows {
    let visibleSections = visibleRows.map({$0.section})
}

UITableViews store their cells using an NSIndexPath. As a result there is no object for sections. Using the following code we can traverse the table and perform operations using the indexes of visible sections (I'm not sure why you want visible sections since visible only means they are currently on the screen, but whatever).

for (NSIndexPath* i in [yourTableViewName indexPathsForVisibleRows])
{
  NSUInteger sectionPath = [i indexAtPosition:0];
  //custom code here, will run multiple times per section for each visible row in the group
}