iOS swift UIImageView改变tableView单元格中的图像[英] iOS swift UIImageView change image in tableView cell

本文是小编为大家收集整理的关于iOS swift UIImageView改变tableView单元格中的图像的处理方法,想解了iOS swift UIImageView改变tableView单元格中的图像的问题怎么解决?iOS swift UIImageView改变tableView单元格中的图像问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

我在 tableView 自定义 cell 中有一个奇怪的问题.对于像图像动作,我在自定义 cell 中编写这些代码,称为 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")
    }
}

和 TableViewController:

func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "FeedCell", for: indexPath) as! FeedViewCell

    return cell
}

但正如您在 this 视频当我触摸索引 0 中的点赞按钮并更改图像时,索引 3 中的点赞按钮也会更改图像.大家能告诉我我的错误吗?

谢谢

推荐答案

尝试 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)
        }else{
                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!) {
            selectedindex.removeObject(selectindex!)
        }else{
              selectedindex.addObject(selectindex!)
        }
        self.tableview.reloadData()
    }

本文地址:https://www.itbaoku.cn/post/924646.html