我有一个表视图,其选择设置为单选。这是一系列操作:
- 单击此表中的一个单元格,出现第二个屏幕,其中显示
- 所选单元格实体的详细信息
- 此屏幕上的“后退”按钮会将视图带回到第一个屏幕,即。表格视图
- 在此(“表格视图”)屏幕上,我的目标是使先前选择的单元格保持突出显示。说,背景为红色
- 然后单击另一个单元格,再次出现第二个屏幕,显示新单元格的详细信息
- 回到第一个屏幕后,新选择的单元格现在突出显示,而先前选择的单元格则未突出显示。
步骤5出了问题:
一个。步骤5之后,新选择和旧选择的单元格都以红色突出显示
b。 didDeselectRowAt()函数似乎没有被调用
这是我用Swift 5编写的代码:
extension MainViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: “detailSegue”, sender: self)
let cell = tableView.cellForRow(at: indexPath)
cell?.backgroundColor = .red
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
print("--------- deselect cell at \(indexPath.row)") // this line did *not* appear in debugger
let cell = tableView.cellForRow(at: indexPath)
cell?.backgroundColor = .clear
}
}
还共享更多代码以显示更多上下文。
子类UITableViewCell:
import UIKit
import SwipeCellKit // from cocoa pod
class CarCell: SwipeTableViewCell {
// bunch of IBOutlet’s, omitted for clarity
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
backgroundColor = selected ? .red : .clear
}
}
cellForRowAt:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: K.carCellIdentifier, for: indexPath) as! CarCell
cell.delegate = self
if let currentCar = cars?[indexPath.row] {
// lots of actions to render the IBOutlet’s for the particular CarCell, omitted for clarity
} else {
cell.regoLabel.text = "No Cars Added Yet"
}
return cell
}
如果有人能给我一些启发,我将不胜感激。