Search code examples
iosuitableviewscrollviewnsindexpath

iOS: scrollToRowAtIndexPath doesn't display correct top indexpath for last page


I am trying to scroll tableview programmatically as coded following. Please note that I have increased the content size so I can see few last few remaining rows. I can scroll manually correctly to get required indexpath at top but programmatically it's not happening.

[tableview reloadData];

CGSize size = tableview.contentSize;
size.height += 1000;
tableview.contentSize = size;

int rows = [tableview numberOfRowsInSection:0];
int numberofRowsInView = 17;
for (int i = 0; i < ceil((float)rows/numberofRowsInView); i++) {
    [tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:i * numberofRowsInView inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    ....
}

For total rows 60, I expect this code to return cell views of 0-16, 17-33, 34-50, 51-59 but for the last scroll it returns 43-59 i.e. full 17 rows view while based on above code, top indexpath should be 51 for the last page!

Can someone please help me to sort this out. Thanks.

This is manually scrolling image:

Manually scrolling

This is done programmatically:

Programmatically scrolling


Solution

  • It seems I am not going to get this working. I need last page cells only for fraction of time and then I reset back to original tableview frame.

    int rows = [tableview numberOfRowsInSection:0];
    int numberofRowsInView = 17;
    
    for (int i = 0; i < ceil((float)rows/numberofRowsInView); i++) {
        NSUInteger remainingCells = rows - i*numberofRowsInView;
        if(remainingCells < numberofRowsInView) {
            CGRect frame = tableview.frame;
            frame.size.height = remainingCells * tableview.rowHeight;
            tableview.frame = frame;
        }
    
        [tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:i * numberofRowsInView inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
         ......
    
      }
    

    Now it shows exactly remained cells on last page! I don't need to set contentSize anymore.