我有一个奇怪的问题。当我选择一个单元格并更改一个 UIView 组件的背景颜色时,然后我向下滚动并选择单元格将超出 View 范围。我确实选择了新单元格 -> 前一个单元格应该未被选中,但事实并非如此。因为当我返回时,我确实有 2 个选定的单元格。
var lastSelectedAtIndexPath: IndexPath?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch tableView {
case myTableView:
if let cell = myTableView.cellForRow(at: indexPath) as? MyTableViewCell {
cell.checkMarkBorder.backgroundColor = UIColor.darkGreyFts
lastSelectedFuelAtIndexPath = indexPath
}
default:
break
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
switch tableView {
case myTableView:
if let cell = fuelTableView.cellForRow(at: indexPath) as? MyTableViewCell {
cell.checkMarkBorder.backgroundColor = UIColor.white
}
default:
break
}
}
还有 cellForRowAt
我有:
let cell = myTableView.dequeueReusableCell(withIdentifier: "myCell") as! MyTableViewCell
if let lastIndexPath = lastSelectedFuelAtIndexPath {
myTableView.deselectRow(at: lastIndexPath, animated: true)
}
cell.myImage.image = UIImage(named: fuelType)?.withRenderingMode(.alwaysTemplate)
cell.myNameLabel.text = "Test"
知道发生了什么事吗? 提前致谢!
最佳答案
不要在 cellForRowAt
之外的单元格上进行更改始终更改数据源并在 cellForRowAt
中使用数据源,然后在 didSelectRowAt
和 didDeSelectRowAt 中使用
重新加载该行。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = myTableView.dequeueReusableCell(withIdentifier: "myCell") as! MyTableViewCell
cell.myImage.image = UIImage(named: fuelType)?.withRenderingMode(.alwaysTemplate)
cell.myNameLabel.text = "Test"
cell.checkMarkBorder.backgroundColor = lastSelectedFuelAtIndexPath == indexPath ? UIColor.darkGreyFts : UIColor.white
return cell
}
现在在 didSelectRowAt
和 didDeSelectRowAt
中更新 lastSelectedFuelAtIndexPath
重新加载行。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == myTableView {
lastSelectedFuelAtIndexPath = indexPath
myTableView.reloadRows(at: [indexPath], with: .automatic)
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if tableView == myTableView {
lastSelectedFuelAtIndexPath = nil
myTableView.reloadRows(at: [indexPath], with: .automatic)
}
}
关于swift - 向后滚动时单元格不会被取消选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44822369/