本文介绍了双击 UITableView 单元格应该转到以前的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我选择(单击)TableView 的行,它应该添加 Image 说我选择了这个特定的项目.它工作正常!
If I select (click) row of TableView, it should add Image saying that I selected this particular Item. It's working fine!
我的问题是:如果用户想从所选项目移回.如果我点击同一行,它应该取消选择该单元格并隐藏该图像.
My problem is: if user want to move back from that selected item.If I click on the same row it should deselect that cell and hide that image.
我尝试的是:
func tableView (_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath) as! leistungCell
// Configure the cell...
let tableData = self.tableData[indexPath.row]
cell.leistungLbl.text = tableData["leistung_info"] as? String
//space between Rows
cell.contentView.backgroundColor = colorLightGray
cell.contentView.layer.borderColor = UIColor.white.cgColor
//space between Rows
cell.contentView.layer.borderWidth = 3.0
cell.contentView.layer.cornerRadius = 8
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell?.imageView?.image = UIImage(named: "check.png")
let value = Info["leistung_info"] as! String
}
func tableView(_ tableView: UITableView, didDeSelectRowAt indexPath: IndexPath){
let cell = tableView.cellForRow(at: indexPath)
cell?.imageView?.image = nil
}
推荐答案
忘记并删除 didDeSelectRowAt
,只需使用 didSelectRowAt
和一个数组来保存选择:
Forget and remove didDeSelectRowAt
, just use didSelectRowAt
, and an array to save selections:
var selectedIndexPaths = [IndexPath]()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
if let index = selectedIndexPaths.index(of: indexPath) { //deselect it if the row is selected
tableView.deselectRow(at: indexPath, animated: true)
cell?.imageView?.image = nil
selectedIndexPaths.remove(at: index)
}
else{ //select it if the row is deselected
cell?.imageView?.image = UIImage(named: "check.png")
selectedIndexPaths.append(indexPath)
}
}
并注意细胞正在重用!请在 cellForRowAt
方法中做同样的检查.
And be aware of that the cells are being REUSED ! Please do the same check in cellForRowAt
method.
这篇关于双击 UITableView 单元格应该转到以前的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!