且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

iOS swift UIImageView更改tableView单元格中的图像

更新时间:2022-11-23 08:44:58

尝试 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()
    }