amelian amelian - 1 year ago 190
iOS Question

Swift - Best way to reload UITableView data avoiding freeze

SSome with experience can tell me what is the best way to execute a reloadData() from a UITableView on swift avoiding freeze?

I have a ViewController with a TableView, this shows a list of users in pairs of 10 rows. When the scroll show the last row - 1, in a background, the app request the next 10 users and then they are added to the rest of users for show now 20 users in the TableView.

When this is executed with a delegated method, the reload causes a freezing around 1~2 seconds and hasn't a comfortable navigation.

Any idea to solve this? Many thanks

Answer Source

When new data coming, you don't need to reload the whole tableView. You just need to insert new rows accordingly. That won't cause any lag/freeze.

func didFinishLoadNewUsers(newUsers: [User]) {
    //array of index paths for new rows at the bottom
    var indexPaths = [NSIndexPath]()
    for row in (currentUsers.count..<(currentUsers.count + newUsers.count)) {
      indexPaths.append(NSIndexPath(forRow: row, inSection: 0))
    //update old data
    //insert new rows to tableView
    tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)