在UIContextualAction回调中调用tableView.selectRow无效

时间:2019-05-29 14:47:29

标签: swift uikit tableview

selectRow(at:animated:scrollPosition:)回调中调用UIContextualAction时,没有任何变化:指定的行不会变成灰色。

这是我能写出的最简单的代码,显示出这个问题:

override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, callback in
        tableView.selectRow(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .none)
        callback(true)
    }

    return UISwipeActionsConfiguration(actions: [deleteAction])
}

我尝试了许多变体:

  • 正确执行删除操作(更新模型,然后使用deleteRows()更新表视图)
  • 不对选择操作进行动画处理
  • 使用.normal动作代替.destructive动作
  • tableView.performBatchUpdates()块中将回调代码的各个部分分组
  • performBatchUpdates()调用内外以各种顺序调用所有这些方法
  • 以某种方式等待CATransaction.setCompletionBlock()删除动画的结束
  • 在主队列上分派选择操作,以使其稍后执行记录操作

一切都没有成功。

2 个答案:

答案 0 :(得分:0)

使选择操作成功的一种临时方法是使用计时器,以便在删除动画结束后调用selectRow()

override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, callback in
        Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in
            tableView.selectRow(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .none)
        }
        callback(true)
    }

    return UISwipeActionsConfiguration(actions: [deleteAction])
}

这显然不是一个干净的解决方案,因为它取决于动画在未来iOS版本中不更改的时间,并且需要编写额外的代码来确保选择操作在0.5秒后仍有效(当计时器触发时) (在此示例中我没有这样做)。

答案 1 :(得分:0)

在特定的删除操作情况下,您可以实现tableView(tableView: cell: indexPath:)委托方法,然后在其中执行选择:

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    tableView.selectRow(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .none)
}