2017-05-31 26 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方法中執行相同的檢查。 –

相關問題