Search code examples
uitableviewswift4reloaddatareloadrows

Swift4 : How to use reloadData & deselectRow in UITableViewController?


I try to reloadData on UITableView at viewWillApper. But deselectRow Animation is not working well. How can I do reloadData & deselectRow animation?

override func viewWillAppear(_ animated: Bool) {

    self.tableView.reloadData()
    if let indexPathForSelectedRow = tableView.indexPathForSelectedRow {
            self.tableView.deselectRow(at: indexPathForSelectedRow, animated: true)
    }
    super.viewWillAppear(animated)
}

and below is different. Fade animation duration is little bit short.

override func viewWillAppear(_ animated: Bool) {

    if (self.tableView.indexPathForSelectedRow != nil){
        self.tableView.reloadRows(at: [self.tableView.indexPathForSelectedRow!], with: .fade)
    } 

    super.viewWillAppear(animated)
}

Solution

  • Instead of reloading the whole table, you can just update the contents of the cell directly:

    override func viewWillAppear(_ animated: Bool) {
        let indices = self.tableView.indexPathsForVisibleRows ?? []
        for index in indices {
           guard let cell = self.tableView.cellForRow(index) else { continue }
           cell.textLabel?.text = textDataArray[index.row]
        }
    
        super.viewWillAppear(animated)
    }