save selected row in UITableView after reloadData

后端 未结 14 1025
后悔当初
后悔当初 2020-12-24 11:20

I write custom jabber client in iphone.

I use xmppframework as engine.

And I have UITableViewController with NSMutableArray for repesent contact list.

<
14条回答
  •  无人及你
    2020-12-24 12:10

    Edit:

    After testing, it doesn't always work!,

    the reason is the index may change !

    so the correct way is
    make new variable

    var currentIndex : IndexPath?
    

    and on didSelectRow

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
            currentIndex = indexPath
    }
    

    then change the function to

     func reloadTableView() {
            let indexPaths = tableview.indexPathsForSelectedRows
            if let currentIndex = self.currentIndex {
            self.tableview.reloadRows(at: [currentIndex], with: .fade)
            for path in indexPaths ?? [] {
                tableview.selectRow(at: path, animated: false, scrollPosition: .none)
                }}
        }
    

    ==========

    @marmor Answer worked

    this is a Swift version of his code

    Swift 4.2.3

    func reloadTableView() {
            let indexPaths = tableView.indexPathsForSelectedRows
            tableView.reloadData()
            for path in indexPaths ?? [] {
                tableView.selectRow(at: path, animated: false, scrollPosition: .none)
            }
        }
    

提交回复
热议问题