Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change image on select within tableview cell - Swift

I am trying to change an image within a cell when it is selected. Here is what I have in my view controller:

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

let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomTableViewCell

        cell.bgImage.image = UIImage(named: "second_image")

}

This is where I set the image:

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

let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomTableViewCell

cell.bgImage.image = UIImage(named: "first_image")

}

When I select the cell, the image does not update. How do I get this to work?

like image 782
Katie H Avatar asked Jan 05 '16 20:01

Katie H


3 Answers

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath) as! CustomTableViewCell
cell.bgImage.image = UIImage(named: "second_image")}

For Swift 3+:

func tableView(tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell
cell.bgImage.image = UIImage(named: "second_image")}
like image 58
Paul Razvan Berg Avatar answered Sep 23 '22 14:09

Paul Razvan Berg


The issue is probably that you are calling dequeueReusableCellWithIdentifier. Try using cellForRowAtIndexPath instead (documentation about it here). This will give you a reference to the current cell, rather than a reference to a new reusable cell.

So, according to your code above:

let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! CustomTableViewCell

This typecast is critical because cellForRowAtIndexPath returns UITableViewCell, which will not have the bgImage member.

Also, make sure that you have a member called bgImage that is a UIImageView in your CustomTableViewCell class by adding @IBOutlet strong var bgImage: UIImageView!, and that said IBOutlet is connected in your storyboard/xib.

like image 26
Leejay Schmidt Avatar answered Sep 25 '22 14:09

Leejay Schmidt


Can't you simply use the .hightlightedimage value for the imageView? I'm doing the following in my cellForRowAt func:

cell.imageView?.image = UIImage(named: "\(indexPath.row).png")
cell.imageView?.highlightedImage = UIImage(named: "\(indexPath.row)g.png")

And I've just named the necessary images "0.png" and "0g.png" etc to make sure the image and highlighted image match up. Of course, that's a small static array, if you were using coreData with a larger array you could simply hold the imageName and the hightlightedImageName in the data set and pull the info from there.

like image 36
Zachary Fisher Avatar answered Sep 23 '22 14:09

Zachary Fisher