2017-06-14 12 views
0

後の初期のセルに添付滞在ではないが、リロードがトリガされるたびに、新たに追加されたセルが変更された画像の代わりに、古いものを持っています。これは私のcellForRowAtです:ボタンは、私が押された後の画像を変更するカスタムセル内のボタンを持ってリロード

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "Sender", for: indexPath) as! Sender 
     cell.clearCellData() 
     cell.message.text = self.items[indexPath.row].content 
     cell.name.text = self.items[indexPath.row].name 
     cell.from = self.items[indexPath.row].fromID 
     return cell 
    } 

ボタンのアウトレットとアクションは次のようにボタン電池の両方である:

@IBAction func downVoted(_ sender: Any) { 
    if(self.downVote.image(for: .normal) == #imageLiteral(resourceName: "DownGray")){ 
     self.downVote.setImage(#imageLiteral(resourceName: "DownOn"), for: .normal) 
    }else{ 
     self.downVote.setImage(#imageLiteral(resourceName: "DownGray"), for: .normal) 
    } 
} 

新しい行が追加されるまで、それは正常に動作します。私は、ボタンタグをセルタグと同じように設定しようとしましたが、それは助けになりませんでした。誰かがこれに対する修正を知っていますか?

ありがとうございます。

+0

を行うことを忘れないでください、と'cellForRowAt'に適切な画像をセットします。簡単な例として、この質問の私の答えを見てください:https://stackoverflow.com/questions/44393575/checkbox-uitableview-with-different-sections/44398444#44398444 – DonMag

答えて

1

これは、セルが再利用されているために、画像をcellForRowAt:に設定しようとすると、モデルにbool(選択されているかどうか)が必要なため、代理人を使用して実装する必要がありますそれあなたがインデックスであなたのモデルを変更し、テーブルビューをリロードすることができますので、あなたのコントローラで、私はサンプルコード

protocol SenderDelegate { 
    func downVoteTapped(_ cell: MainTVCell) 
} 

class Sender: UITableViewCell { 
    @IBAction func downVoted(_ sender: Any) { 
     delegate!.downVoteTapped(self) 
    } 
} 
を提供

とコントローラ

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "Sender", for: indexPath) as! Sender 
     cell.clearCellData() 
     cell.delegate = self 
     cell.message.text = self.items[indexPath.row].content 
     cell.name.text = self.items[indexPath.row].name 
     cell.from = self.items[indexPath.row].fromID 
     if self.items[indexPath.row].selected == true { 
      self.downVote.setImage(#imageLiteral(resourceName: "DownOn"), for: .normal) 
     } else { 
      self.downVote.setImage(#imageLiteral(resourceName: "DownGray"), for: .normal) 
     } 
     return cell 
    } 

func downVoteTapped(_ cell: Sender) { 
    let index = tableView.indexPathForCell(cell)?.row)! 
    self.items[index].selected == !self.items[index].selected 
    tableView.reloadData() 
} 

とあなたがあなたのテーブルのデータの残りの部分と一緒にボタンの「状態」を追跡する必要がありSomeViewController: SenderDelegate し、モデルにvar selected = false

0

これは、呼び出されるたびにボタンの状態を cellForRowAt indexPath:デリゲートメソッドに設定する必要があるためです。 したがって、ボタンの状態をどこかに格納する必要があります。配列またはplistにすることができます。

あなたはあなたのアイテムを配列に保存しました。それにvar isLiked: Boolのプロパティを追加することをお勧めします。ボタンを押すとそのプロパティを変更する必要があります。そのプロパティに応じて、選択したイメージまたは選択されていないイメージをあなたのcellForRowAt indexPath:メソッド

関連する問題