如何在tableView中删除行后立即选择另一行(Swift)

时间:2018-12-03 11:01:26

标签: ios swift uitableview

我正在删除行,并希望获得下一个行为:

  1. 如果要删除所选行,则需要自动选择另一行。
  2. 如果还有其他麻烦,在执行删除操作时,将要自动选择要删除的目标行,我不需要选择它,因为我只想删除它。

目前的主要问题是1。

我知道也许行:0不再存在,但现在t不是重点,我只是简化了代码以使其更舒适地讨论这一点。我尝试了performBatchUpdates,并尝试将selectRow(at:section :)也移至完成关闭,行选择也不起作用。

selectRow在insertRows函数之后可以很好地工作,所以我很困惑。

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)

    }
}

2 个答案:

答案 0 :(得分:1)

好吧,我找到了第一个问题的解决方案(只是认为也许可以存在该函数并键入 didrowat ,而xcode建议使用此 didEndEditingRowAt :)

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

现在问题的第一部分已经回答,我在此处插入了选择。

第二个问题仍未解决,当我删除另一行时如何使选定的行保持选中状态。如果要删除另一行,则根本不需要取消选择行。

答案 1 :(得分:0)

据我了解您的问题,找到以下解决方案:

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)
    }
}

在删除行时以及在endUpdates之后传递indexPath,只需设置与SelectedRow相同的indexPath即可。