maxisme
maxisme

Reputation: 4245

How to go to the first cell in UITableView after reloading data

Currently when I reload the data in the table it stays in the same scroll position:

[self.tableView reloadData];

How can I get the scroll position/height to go back to the top/the first cell?

Upvotes: 0

Views: 2659

Answers (3)

Paul K.
Paul K.

Reputation: 95

I got this crash because I was trying to scroll to row 0 section 0 of an empty tableView. Make sure your tableData.count > 0 before you execute the scrollToRow().

Upvotes: 1

Mehdi Chennoufi
Mehdi Chennoufi

Reputation: 2211

Swift 4 version

let indexPath = IndexPath(row: 0, section: 0)
tableView.scrollToRow(at: indexPath, at: .top, animated: false)

Upvotes: 3

JoeFryer
JoeFryer

Reputation: 2751

You can use the following method to scroll to any index path in your table view:

[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];

So, for the first cell, your indexPath would be:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

You can change the scrollPosition and animated parameters to get your desired effect/result.

Upvotes: 4

Related Questions