2017-07-29 15 views
0

我有一個tableView,當選擇將圖像從一個更改爲另一個。這一切工作正常,但是當我選擇一個tableCell時,它會更改圖像,但是當我滾動它時,它也改變了我沒有選擇的另一個單元格的圖像。複選框上的複選框,斯威夫特,iOS

以下是我的代碼。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "FeaturesCell") as! FeaturesCell 

    cell.featuresLabel.text = self.items[indexPath.row] 

    return cell 

} 

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 

    pickedFeatures.append(items[indexPath.row]) 

    let cell = tableView.cellForRow(at: indexPath) as! FeaturesCell 

    cell.checkImage.image = #imageLiteral(resourceName: "tick-inside-circle") 

} 

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { 
    pickedFeatures.remove(at: pickedFeatures.index(of: items[indexPath.row])!) 

    let cell = tableView.cellForRow(at: indexPath) as! FeaturesCell 

    cell.checkImage.image = #imageLiteral(resourceName: "No-tick-inside-circle") 
} 

如果在did選擇功能中使用了detqueureusable單元,那麼它在選擇時根本不會改變圖片。

+0

這會回答你的question-:HTTPS://stackoverflow.com/questions/43686354/filtertableviewcontroller-reloadrows-reloading-rows-only-on-first-call。您實際上需要保存複選框狀態。 –

+0

這裏是我的演示https://www.dropbox.com/s/e43zk55surlwjlk/CollectionCkeck.zip?dl=0它與collectionview但邏輯可能會幫助你 –

回答

1

您可以使用tableView.dequeueReusableCell(_),問題是,您沒有保持所選單元格的狀態。

例子:

class viewController: UIVieWController, UITableViewDelegate, UITableViewDataSource { 

    var selectedCellList = [IndexPath]() 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "FeaturesCell") as! FeaturesCell 

     cell.featuresLabel.text = self.items[indexPath.row] 

     if let _ = selectedCellList.index(of: indexPath) { 
      // Cell selected, update check box image with tick mark 
      cell.checkImage.image = #imageLiteral(resourceName: "tick-inside-circle") 
     } else { 
      // Cell note selected, update check box image without tick mark 
      cell.checkImage.image = #imageLiteral(resourceName: "No-tick-inside-circle") 
     } 
     return cell 
    } 

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 

     pickedFeatures.append(items[indexPath.row]) 

     if let index = selectedCellList.index(of: indexPath) { 
      selectedCellList.remove(at: index) 
     } else { 
      selectedCellList.append(indexPath) 
     } 
     tableView .reloadRows(at: [indexPath], with: .automatic) 
    } 

} 
+0

謝謝@Subramanian。這工作完美,但你的解釋也是一個幫助。有時候可以通過一些小的解釋來讓其他程序員變得更好。非常感謝你的幫忙。祝一切順利。 –