简体   繁体   中英

How to get Last Selected row and Current Selected Row from UITableview swift?

I am trying to get the previously selected row and the currently selected row from the UITableview didSelectRowAt method.

The didSelectRowAt method only provides the row that was selected.

Is there a way to know which row was selected before didSelectRowAt was called?

You just need to declare two properties to store the previously and currently selected rows, then update their values in tableView(_:didSelectRowAt:) .

class TableViewController: UITableViewController {
    var lastSelectedRow: IndexPath?
    var currentlySelectedRow: IndexPath?

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        super.tableView(tableView, didSelectRowAt: indexPath)
        lastSelectedRow = currentlySelectedRow
        currentlySelectedRow = indexPath
    }
}

The UITableViewDelegate protocol has several methods to help you manage the state of your table view.

Do not cache IndexPaths as they can easily become stale and invalid. Your code will eventually encounter an invalid IndexPath and the application will crash when the invalid object is used.

Instead, use the methods that inform you what row is going to be selected. Within the willSelectRowAt you can then get the current selection state of the table view by calling indexPathForSelectedRow and perform the actions you want with the selection information.

class TableViewController: UITableViewController {

     override func tableView(UITableView, willSelectRowAt: IndexPath) -> IndexPath? {
          let selectedIndexPath = self.tableView.indexPathForSelectedRow()
          // Do something with the selected path
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM