我无法理解为什么我无法切换选定的表格行。 我在didSelectRowAt中成功设置了accessoryType。 但我似乎无法在didDeselectRowAt中将accessoryType设置为none。
我的数据:
serviceItems = ["Heater", "Air Conditioner", "Boiler", "Heat Pump"]
这是我的tableview覆盖:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.accessoryType = .checkmark
let serviceItem = serviceItems[indexPath.row] as! String
cell.textLabel?.text = serviceItem
}
// does not remove checkmark
// does not change textLabel to "test"
// DOES print "DESELECTING" (so I know its getting called)
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.accessoryType = .none
cell.textLabel?.text = "test"
print("DESELECTING")
}
答案 0 :(得分:5)
应该使用tableView.cellForRow
代替tableView.dequeueReusableCell
更改:
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
要:
let cell = tableView.cellForRow(at: indexPath)
答案 1 :(得分:1)
我把所有东西放在DidSelectRow中看到了这里:
func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath)
{
if let cell = tableView.cellForRow(at: indexPath) {
if self.selectedIndexPaths.contains(indexPath)
{
// Config Cell
cell.accessoryType = .none
self.selectedIndexPaths.remove(indexPath)
}
else
{
// Config Cell
cell.accessoryType = .checkmark
self.selectedIndexPaths.add(indexPath)
}
// anything else you wanna do every time a cell is tapped
}
}