I have a tableViewController and for it I created a separate class. In this class there is a method:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("postCell", forIndexPath: indexPath) as! CustomPostCellTableViewCell cell.likeBTN.tag = indexPath.row cell.likeBTN.addTarget(self, action: #selector(FeedVC.likeClick(_:)), forControlEvents: .TouchUpInside) return cell } 

I can access any custom cell element through the cell. But inside this function. But I have one more function that works when I press a button in a cell. In this function, I get the cell number. But how can I now access the element of the desired cell and change it from this function (below)?

  @IBAction func likeClick (sender: UIButton){ let indx = NSIndexPath(index: sender.tag) print(indx) } 

The task is as follows: I have in the table the posts in each cell. And in every post there is a button like. Clicking on the button should change the number of likes. How to implement this?

  • what you tried, what did not work? - Max Mikheyenko
  • What exactly fails to update the desired cell (reload) / send any request / change something in the model? - VAndrJ
  • @VAndrJ I tried in the likeClick function to declare a variable let cell = tableView.dequeueReusableCellWithIdentifier ("postCell", forIndexPath: indexPath) as! CustomPostCellTableViewCell only substituted instead of indexPath the index derived from the tag. - cheerful_weasel
  • As a result, it gives an error. So there even before the update did not come. I simply do not even know how to properly access the desired cell. - cheerful_weasel
  • @MaxMikheyenko I wrote a little higher in the comments that I tried. But in fact, I did it at random, because I don’t know how to address a specific element of any cell from another function? Those. for example, changing the value of the text box of cell number 10 so that it appears immediately. I’m aware of the update, but before the update you must first change the value in the cell. - cheerful_weasel

1 answer 1

In general, it dawned on me that I didn’t need to access the cell. I just need to make changes to the desired element of the array and then just update the cell.

  @IBAction func likeClick (sender: UIButton){ let ind = sender.tag let indx = NSIndexPath(forRow: ind, inSection: 0) print(indx) allposts[ind].postlikes = 100 self.tableView.reloadRowsAtIndexPaths([indx], withRowAnimation: UITableViewRowAnimation.Fade) } 

And the error occurred because the NSIndexPath was incorrectly set. He needs to specify the section number (in my case, always 0) and the line number.