首先,创建一个变量来存储TableViewController中的先前位置:
var previousPosition: IndexPath?
然后,一旦你点击一个单元格,就存储这个位置:
override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
previousPosition = indexPath
}
最后,当呈现的UIActionSheet 被关闭时(后面的后退按钮示例),下面的代码 sn-p 选择并聚焦触发了最新点击的表格视图单元格:
var actionSheet: UIAlertController?
actionSheet = UIAlertController(title: "Action Sheet",
message: "Ready to go back?",
preferredStyle: .actionSheet)
let backButton = UIAlertAction(title: "B.A.C.K.",
style: .cancel,
handler: { (action) -> Void in
print("Back button tapped")
self.tableView.selectRow(at: self.previousPosition,
animated: true,
scrollPosition: .none)
let currentCell = self.tableView.cellForRow(at: self.previousPosition!)
UIAccessibility.post(notification:.layoutChanged,
argument: currentCell)
})
actionSheet!.addAction(backButton)
在一个空白项目中检查此代码 sn-p 的结果,并在您的应用中对其进行调整以使其按需要工作。
EDIT:除了我的代码 sn-p 之外,看看表视图的 remembersLastFocusedIndexPath 实例属性,它可以提供直接结果restoresFocusAfterTransition 视图控制器的实例属性。