Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Keep UITableView at the same position when reloadData

I'm running into an annoying problem. I'm doing a messaging app. In the message page, when the user scrolls to the top, as soon as the topmost cell becomes visible, it will load more messages to display. Because at the time of loading more messages, the position of the table view is at the top (content offset is 0), after done loading messages, I call reloadData and iOS tries to maintain the offset which consequentially scrolls to the top of the table view again and triggers another load. This is like an infinite loop until there is no more message to load. I tried to call scrollToRow right after reloadData but no luck.

So anything that can keep the table view at the same position (i.e. if before loading, message "a" is at the top, after loading, message "a" still at the top of the screen) after calling reloadData will work for me.

Spent several hours on this so I'll really appreciate any help. Thanks

like image 827
Son Nguyen Avatar asked Jun 16 '26 17:06

Son Nguyen


1 Answers

I don't know if this help you but you can try this while reloading-

if let indexPaths = tableView.indexPathsForVisibleRows {
    tableView.reloadRows(at: indexPaths, with: .none)
} else {
    tableView.reloadData()
}
like image 109
Nikhil Manapure Avatar answered Jun 21 '26 21:06

Nikhil Manapure



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!