首先,如果您还没有,您需要在点击时标记您的“已选择”:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? SubclassedCell else {
return
}
//`setSelected(:animated:) is built into `UITableViewCell`
cell.setSelected(true, animated: true)
...
然后在viewWillAppear(_:) 中,您将取消选择动画与边缘滑动动画相协调:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//1
guard let selectedIndexPath = tableView.indexPathForSelectedRow else {
return
}
//2
if let transitionCoordinator = self.transitionCoordinator {
transitionCoordinator.animate(alongsideTransition: { (context) in
self.tableView.deselectRow(at: selectedIndexPath, animated: true)
}, completion: nil)
//3
transitionCoordinator.notifyWhenInteractionChanges { (context) in
if context.isCancelled {
self.tableView.selectRow(at: selectedIndexPath, animated: true, scrollPosition: .none)
}
}
} else {
//4
tableView.deselectRow(at: selectedIndexPath, animated: animated)
}
}
代码很多,这里是重点:
- 仅当存在选定的索引路径时才运行此命令。如果您是第一次在此屏幕上,则没有选择。 (顺便说一句,表格视图会跟踪其自己选择的索引路径。您只需将单元格标记为选中或未选中)。
- 将行取消选择动画与当前动画“上下文”(即边缘滑动动画上下文)协调。
- 您可能会在滑动过程中改变主意!如果发生这种情况,您需要重新选择之前取消选择的内容。
- 过去,在过渡协调员之前,您只需添加这一行。如果没有过渡协调器(旧版本的 iOS、在没有动画的情况下返回堆栈等),就会出现这种 else 情况。
好吧..在你放弃 UIKit 之前,知道有一个捷径。
快捷方式:使用UITableViewController 而不是UIViewController
不要继承UIViewController 并添加一个表格视图,只需继承UITableViewController。您仍然需要将您的单元格标记为选中,但仅此而已。
这是因为UITableViewController 有一个名为clearsSelectionOnViewWillAppear 的属性,默认设置为true。它会为您处理一切。