tableViewCellの中にあるボタンを押すと、そのtableViewCellのなかにあるtextView.textの値を変えるプログラムを以下のように書いたのですが、選択したtableViewCell以外のtableViewCellのなかにあるtexttView.textの値も一緒に変わってしまうことがあります。どこでこのようなことが起こっているのかが全く見当がつかないのでわかる方いたら教えてください。
//tableViewCellのクラス class TableViewCell: UITableViewCell { //変えたいtextView @IBOutlet var textView: UITextView! //このボタンを押すと変わる(cellForRowAtでここのボタンにtagをつける) @IBOutlet var changeTextButton: UIButton! } //viewControllerのクラス class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{ //表示させたい文字配列 let texts = ["a","b","c","d","e","f","g","h","i","j","k","l","n","m"] /*viewDidRoadなど省略tableView.delegate、tableView.dataSorceはselfにしている*/ //cellの数 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return texts.count } //cellを返す func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //cellを宣言 let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell //textViewのtextを初期値に変更 cell.textView.text = "ボタンを押してね" //ボタンにtag付け cell.changeTextButton.tag = indexPath.row //cellを返す return cell } } //storyBoardにあるcellからActionで紐付け。textViewのtextを変える @IBAction func changeText(_ sender: Any) { let button = sender as! UIButton let indexPath = IndexPath(row: button.tag, section: 0) let cell = tableView.cellForRow(at: indexPath) as! TableViewCell //代入して指定した番号のcellのtextViewのtextを変えると他のcellのtextViewのtextも変わる(全てではなくいくつかが変わる) cell.textView.text = texts[indexPath.row] } }
回答1件
あなたの回答
tips
プレビュー