2017-05-31 41 views
0

如果我选择(单击)一行TableView,它应该添加图像说我选择了这个特定的项目。它工作正常!双击UITableView单元格应该转到之前的状态

我的问题是:如果用户想从该选定的项目后退。 如果我点击同一行,它应该取消选择该单元格并隐藏该图像。

我想的是:

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 
} 
+0

面临什么问题? – KKRocks

+0

@KKRocks当我再次单击相同的单元格时,我之前选择的图像将不会移动它将仍然可见。我希望该图像能够隐藏在该单元格中。 –

+0

你需要在单元格之后重新加载单元格?.imageView?.image = nil。 – KKRocks

回答

1

忘记和删除didDeSelectRowAt,只要使用didSelectRowAt,并数组保存选择:

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方法中进行同样的检查。

+0

谢谢它的工作! –

+0

很高兴帮助!巴勃罗的编辑改善了选择状态。感谢他。 –

+0

@Spurti,并注意细胞正在被重复使用!请在cellForRowAt方法中执行相同的检查。 –