简体   繁体   中英

Changing custom UIImage in didSelectRowAtIndexPath

I have a custom UIImage within my cell that I need to change when didSelectRowAtIndexPath is called. For some reason the image isn't changing, and I think it's because of my cell declaration inside the method.

class CustomCell: UITableViewCell {

    @IBOutlet weak var indicator: UIImageView!

}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        var cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! CustomCell

        cell.indicator.image = UIImage(named: "newImage")

}

How can I change my UIImage to "newImage" when the cell is clicked?

Create cell from index path

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        var cell = tableView.cellForRowAtIndexPath(indexPath) as! CustomCell

        cell.indicator.image = UIImage(named: "newImage")

}

You need to create a UIImage variable and change that image variable when the tableviewcell is pressed.

For example...

 var imageVar:UIImage = UIImage(named: "IM")

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

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell?

        let ImageView:UIImageView = cell!.viewWithTag(1) as! UIImageView

        ImageView.image = imageVar


}


    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

self.imageVar = UIImage(named: "Image")

self.tableView.reloadData

}

For Swift 5

   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! MembersCell
        cell.member_status.image =  YourImage
}

Also, If want to change only one cell image in case of reusable cell in the table view, and rest others cell image data didn't affect, Similar to radio button functionality. So you can implement as follows:-

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) as? CustomCell {

            cell.indicator.image = UIImage(named: "newImage")
            
        }
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        
        if let cell = tableView.cellForRow(at: indexPath) as? CustomCell {
       
            cell.indicator.image = UIImage(named: "oldImage")
        }
    }

And then the output look like:-

在此处输入图片说明

And the other one:-

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM