【发布时间】:2018-01-24 22:54:16
【问题描述】:
我先关注了这个帖子:How to programmatically select a row in UITableView in Swift 1.2 (Xcode 6.4)
这对选择有帮助,但是当我点击屏幕选择另一行时,之前(以编程方式)设置的行不会触发取消选择消息。自然选择的单元格(通过点击屏幕)会收到取消选择消息。
我需要以编程方式选择的行来接收取消选择消息(非编程方式)。
(我在 UITableView 子类中工作 - 所以它不是委托,而是覆盖)。
我的代码:
if let selectedRow = viewModel.selectedRow {
defaultSelectedPath = IndexPath(row: selectedRow, section: 0)
if let defaultSelectedPath = defaultSelectedPath {
let selectedCell = self.tableView.cellForRow(at: defaultSelectedPath)
self.tableView.selectRow(at: defaultSelectedPath, animated: true, scrollPosition: .none)
self.tableView(self.tableView, didSelectRowAt: defaultSelectedPath)
selectedCell?.accessoryType = .checkmark
}
}
黑客修复:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var cell = tableView.cellForRow(at: indexPath)
cell?.accessoryType = .checkmark
if let defaultSelectedPath = self.defaultSelectedPath {
if indexPath != defaultSelectedPath {
cell = tableView.cellForRow(at: defaultSelectedPath)
tableView.deselectRow(at: defaultSelectedPath, animated: false)
self.tableView(self.tableView, didDeselectRowAt: defaultSelectedPath)
cell?.accessoryType = .none
}
self.defaultSelectedPath = nil
}
}
请告诉我有更好的方法来做到这一点。
【问题讨论】:
-
我不得不写一堆愚蠢的黑客代码,但我想我明白了......
-
你想一次只选择 1 行吗?
-
是的,但默认值是通过程序设置并在加载时显示的。
-
你试过下面的代码吗?
标签: ios uitableview didselectrowatindexpath