I'm trying to make a table with custom cells in swift so far it's going well, but I decided to add a button me gusta
to each cell, the button when pressed simply changes its image, so the problem I have is that: Every time I press the button me gusta
yes it changes the image of the button but it changes it for the cell in which the button is pressed and for others in the same list as shown in the following image:
What happens in the image is that I press the top button but the bottom button also changes (for example), I am trying to reuse the same cell with dequeueReusableCellWithIdentifier
this is my code:
extension ViewController : UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 8
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! DestinoTableViewCell
cell.btnCorazon.tag = indexPath.row
cell.btnCorazon.addTarget(self, action: #selector(changueButon), forControlEvents: .TouchUpInside)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("select", indexPath.row)
}
func changueButon(sender: UIButton){
if(!self.isLove){
if let image = UIImage(named: "heart.png") {
sender.setImage(image, forState: .Normal)
isLove = true
}
}else{
if let image = UIImage(named: "fav.png") {
sender.setImage(image, forState: .Normal)
isLove = false
}
}
}
}
So my question is: Is there a way to fix this problem? And if there is, what is it?
In
DestinoTableViewCell
create a protocol as follows:Later, in your class you declare a property of type weak that is the delegate. This is done in the following way:
Once you have this, you have to use the delegate. To do this, once you press the button, inside the selector, making the call inside the cell class, do the following:
It is important that you implement the cell button action within the cell class.
Finally, in your
ViewController
, inside the methodcellForRowAtIndexPath
, you assign the delegate and implement the delegate's method by extending the ViewController.I hope it has been helpful to you.
All the best.
would that Protocol also work when you have a TableView with sections? I use the tags for a single section and it works perfectly but when adding sections I get an “index out of range” error. Any solution?
Thank you