简体   繁体   中英

How to select another row right after deleting row in tableView (Swift)

I am deleting row and want to get next behavior:

  1. If I am deleting row that was selected, I need to get another row selected automatically.
  2. And also if I have an additional trouble, when I am perform deleting, target row that is going to be deleted selecting automatically, I don't need it to be selected as I want to only delete it.

The main question is 1 for now.

I understand that maybe row: 0 does not exists anymore but t's not a point now, I just simplified code to make it more comfortable to discuss the point. I tried performBatchUpdates, and tried to move selectRow(at:section:) to completion closure as well, row selection not works too.

selectRow works perfectly after insertRows function, so I am confused.

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {

        tableView.beginUpdates()
        tableView.deleteRows(at: [indexPath], with: .fade)
        tableView.endUpdates()

        tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: false, scrollPosition: .middle)

    }
}

Ok, I've found solution for the 1st question (just thought maybe such function can exist and typed didrowat , and xcode suggested this didEndEditingRowAt :)

override func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) {
    tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: .middle)
}

Now first part of question is answered, I've inserted selection there.

The second question is still opened, how to make selected row keeping still selected while I am removing another row. I don't need selected row to deselect at all if I am removing another one.

As I understood your question, find this solution:

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        tableView.beginUpdates()
        tableView.deleteRows(at: [indexPath], with: .fade)
        tableView.endUpdates()
        tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
    }
}

Pass indexPath while deleting a row and after endUpdates, you just need to set the same indexPath as SelectedRow.

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