MohammadReza MohammadReza - 1 year ago 155
iOS Question

iOS swift UIImageView change image in tableView cell

I have a strange problem in

. for like Image action I write these code in Custom
: = true
let CommenttapGestureRecognizer = UITapGestureRecognizer(target:self, action:#selector(likehandleTap))

func likehandleTap(_ sender: UITapGestureRecognizer) {

if == UIImage(named: "like-btn-inactive") { = UIImage(named: "like-btn-active")

} else { = 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?


Answer Source

Try code its working 100%

  var selectindex : Int?
  var selectedindex : NSMutableArray = NSMutableArray()
  @IBOutlet var tableview: UITableView!

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("LikeCell", forIndexPath: indexPath)

        let like: UIButton = (cell.viewWithTag(2) as! UIButton)
        let comment: UIButton = (cell.viewWithTag(3) as! UIButton)
        if selectedindex.containsObject(indexPath.row) {
                like.setBackgroundImage(UIImage.init(named: "like.png"), forState: .Normal)
                like.setBackgroundImage(UIImage.init(named: "like (1).png"), forState: .Normal)
       comment.setBackgroundImage(UIImage(named: "chat.png"), forState: UIControlState.Normal)
        like.addTarget(self, action: #selector(self.CloseMethod(_:event:)), forControlEvents: .TouchDown)
        comment.addTarget(self, action: #selector(self.CloseMethod1(_:event:)), forControlEvents: .TouchDown)

        return cell


 @IBAction func CloseMethod(sender: UIButton, event: AnyObject) {

        let touches = event.allTouches()!
        let touch = touches.first!
        let currentTouchPosition = touch.locationInView(self.tableview)
        let indexPath = self.tableview.indexPathForRowAtPoint(currentTouchPosition)!
        selectindex = indexPath.row
        if selectedindex.containsObject(selectindex!) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download