简体   繁体   中英

Changing Label in only one Cell in Tableview Swift

I have an issue with my app. I can't for the life of me figure out how to fix it. It goes as follows.

I am trying to changing 2 label texts in each cell in the tableview. It is label MODE, and label TIME.

I am sending a byte array from an Arduino that contains the data to display it. One by one I am sending this from the Arduino to see it displays nicely in the tableview. Everything works. But when I try and send a different byte array with a different MODE and TIME, it changes ALL the previous cells. Instead of only updating the new cells with the correct Mode and Time.

Here is my tableview code:

UI Table View Data Source

 @IBOutlet weak var recieveTableView: UITableView!

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

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "RecieveCell", for: indexPath) as! RecieveTableCell
     cell.contentView.backgroundColor = cell.isSelected ? UIColor.darkGray : UIColor.white

     cell.rowNumber.text = "\(indexPath.row + 1)." //You have to + 1 ,because cells are zero based.
     cell.modeLabel.text = "\(recievedModeType)"
     cell.timeLabel.text = "\(String(message))μs"

     return cell
 }

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     print("touched")
     if let cell = tableView.cellForRow(at: indexPath) as? RecieveTableCell {
         cell.contentView.backgroundColor = UIColor.darkGray
     }
 }

recievedModeType is the MODE and message is the TIME.

I have a function that runs when the app receives bytes. So the recievedModeType does update every time I send different types of byte arrays. So in I sense its working like it should, but I am missing something crucial here. If anyone got an idea how I should do this, or give me some tips that would be greatly appreciated.

EDIT

I managed to fix it and will give answer eventually!

You can do this by adding new property

var selectedIndexPath: IndexPath?

and than call:

tableView.reloadData()

You should not call tableView.cellForRow method in didSelectRowAt method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM