seankellycs seankellycs - 1 year ago 61
iOS Question

Determine visible sections of a UITableView when sections have no rows

I am attempting to determine which sections are currently visible in my UITableView. However, sometimes my sections do not have rows and only display their section header. Is there a way to determine, maybe by using the section headers, which sections in my UITableView is currently being displayed? Asking for -(NSArray *)indexPathsForVisibleRows does not work to determine the section, because there are no actual rows that are visible, just the section headers.

Answer Source

The best I can come up with is to use contentOffset and frame.size to compute the visible rectangle and iterate over each section calling rectForSection: and see which ones intersect. Something like:

    NSMutableIndexSet*  indexSet = [NSMutableIndexSet new];
    CGRect              visible = self.tableView.bounds;

    for(NSInteger section = 0 ; section < [self numberOfSections])
        CGRect          sectBounds = [self.tableView rectForSection:section];

        if(CGRectIntersectsRect(sectBounds, visible))
            [indexSet addIndex:section];

    return indexSet;