I have a strange problem in tableView
Custom cell
. for like Image action I write these code in Custom cell
called FeedViewCell
:
self.like.isUserInteractionEnabled = true
let CommenttapGestureRecognizer = UITapGestureRecognizer(target:self, action:#selector(likehandleTap))
self.like.addGestureRecognizer(CommenttapGestureRecognizer)
func likehandleTap(_ sender: UITapGestureRecognizer) {
if self.like.image == UIImage(named: "like-btn-inactive") {
self.like.image = UIImage(named: "like-btn-active")
} else {
self.like.image = UIImage(named: "like-btn-inactive")
}
}
and TableViewController:
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FeedCell", for: indexPath) as! FeedViewCell
return cell
}
but as you see in this video when I touch the like button in index 0 and change the image, the like button in index 3 change image also. can you guys tell me my mistake please?
thanks
Try code its working 100%
Take one array
And in tableview take button instead of image and set unlike image in button and set your images instead of my images
That's why you are changing the image loaded in the
imageView
and then with methodtableView.dequeueReusableCell
you are reusing that cell with the changed image.In iOS
UITableView
andUICollectionView
apply the concept of reusable cells. They don't create one cell for every element of the array; they just create 3-4 cells and then they'll reuse it just changing the content inside. That's a great thing because it allows developers to create tables with hundreds of rows without having memory issues.These are the steps followed by the
tableView
(and alsocollectionView
) to show the array of elements:To solve your problem you have just to check the like in the
cellForRowAtIndexPath
Example: