Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll to the top of a UITableView in iOS 7

In iOS 7, I use the following code to scroll to the top of my UITableView. You have to account for the overlap of the translucent status bar and navigation bar.

[tableView 
    setContentOffset:CGPointMake(
        0.0, 
        -tableViewController.topLayoutGuide.length
    ) 
    animated:YES
];

This works only works after the first time you call it. On the first time you call it, my table gets scrolled much farther than it should, showing a lot of white space. Additionally, the UIRefreshControl appears frozen. You have to nudge the table a little to make it bounce back to the true top. Afterwards, you can call this code as many times as you want and it behaves as you'd expect it.

enter image description hereenter image description here

I've tried other ways, but they all have problems. The iOS 6 way behaves just as oddly on the first call. Although it doesn't jump a huge amount on subsequent calls, they are not correct because it scrolls to 64.0 points below the top of the table because we forgot to account for the status and navigation bar.

[table setContentOffset:CGPointZero animated:YES];

I've also tried scrolling to the first cell, but it doesn't scroll to the very top in one call. It will only scroll up one page's worth every time you call it.

[tableView 
    scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] 
    atScrollPosition:UITableViewScrollPositionTop 
    animated:YES
];
like image 940
Pwner Avatar asked Nov 29 '22 07:11

Pwner


1 Answers

Try this one:

     NSIndexPath* top = [NSIndexPath indexPathForRow:NSNotFound inSection:0];
    [tableView scrollToRowAtIndexPath:top atScrollPosition:UITableViewScrollPositionTop animated:YES];

In SWIFT

    let top = NSIndexPath(forRow: NSNotFound , inSection: 0)
    tableView.scrollToRowAtIndexPath(top, atScrollPosition: .Bottom, animated: true)

Swift 4.0 and above

 let top = NSIndexPath(row: NSNotFound, section: 0)
 tableView.scrollToRow(at: top as IndexPath, at: .bottom, animated: true)
like image 199
Dhaval Bhadania Avatar answered Dec 06 '22 17:12

Dhaval Bhadania