UITableView indexPathsForVisibleRows returns wrong rows

Viewed 2927

In my iOS 7 app, I have my view set to "extend edges under top bars" so my uitableview has the translucent effect when you scroll it under the navigation bar as you are scrolling down. But when you scroll back to the top, or when it loads, it properly positions the first cell below the nav bar, not underneath it.

The problem is, that indexPathsForVisibleRows sees the cell underneath the nav bar. So for example, if we scroll down so that all we see is cell index 1 (the 2nd cell), cell index 0 is underneath the nav bar and when we call indexPathsForVisibleRows, it returns index 0 instead of index 1 as the lowest cell that is visible.

Any other way around this?

2 Answers

The Safe Area is the name of the area of the table view that does not contain any translucent bars. Add a category on UITableView to return the rows in the safe area as follows:

UITableView+SafeArea.h

@interface UITableView (SafeArea)

- (NSArray<NSIndexPath *> *)sa_indexPathsForSafeAreaRows;

@end

UITableView+SafeArea.m

@implementation UITableView (SafeArea)

- (NSArray<NSIndexPath *> *)sa_indexPathsForSafeAreaRows{
    return [self indexPathsForRowsInRect:self.safeAreaLayoutGuide.layoutFrame];
}

@end
Related