codddeer123 codddeer123 - 4 years ago 92
Swift Question

didSelectRowAt doesn't affect cellForRowAt

I'm trying to get different label text when UITabelViewCell is pressed but I can't get it working. The default value of

completed
is false, when touched it should be true and then label should be changed. Inside the didSelectRowAt the
completed
value is different so it's good but I can't pass it to cellForRowAt.

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var listItems : [ListItem] = []

@IBOutlet weak var plusButton: UIButton!
@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
//...
}


func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listItems.count
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var item = listItems[indexPath.row]

item.completed = !item.completed // changing from true to false and rom false to true
tableView.reloadData()
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? CellData{
let item = listItems[indexPath.row]
cell.nameLabel.text = item.name
cell.userLabel.text = item.addedBy

if(item.completed == true){ //didSelectRowAt doesn't affect this item.completed
cell.doneLabel.text = "done"
} else {
cell.doneLabel.text = "not"
}
return cell
} else{
return CellData()
}
}
}


ListItem.swift:

struct ListItem{
var name : String!
var addedBy : String!
var completed : Bool!

init(name: String, addedBy: String, completed: Bool){
self.name = name
self.addedBy = addedBy
self.completed = completed
}

}

Answer Source

Your ListItem is a struct when you update it, it doesn't updated on the list as struct is always copied. I think you should do something like :

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  var item = listItems[indexPath.row]
  item.completed = !item.completed //
  listItems[indexPath.row] = item
   tableView.reloadData()
 }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download