John B.
John B.

Reputation: 682

Swift: Setting a new UIImage in CellForRowAtIndexPath does not show up

this is my issue: I am working on an iOS App in Swift. I have a table view which represents meetings. I have created a custom cell. This cell contains an image. A default one is set in the storyboard.

Now depending on the current row data, I want to visualize, if the meeting is expired or new.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCellWithIdentifier("meetingListCell", forIndexPath: indexPath) as! MeetingListCell
     let meeting = meetingList![indexPath.row]

     cell.meeting.text = meeting.text

     if(meeting.isExpired()) {
         cell.meetingIconImageView.image = UIImage(named: "meeting-expired")
     } else {
         cell.meetingIconImageView.image = UIImage(named: "meeting-new")
     }
     cell.setNeedsLayout()
     cell.setNeedsDisplay()
     return cell
 }

But it just does not change the image. Maybe this is a silly one but actually it drives me nuts ;-)

Many thanks in advance Cheers John

Upvotes: 1

Views: 290

Answers (2)

ArturOlszak
ArturOlszak

Reputation: 2663

I would debug it with those steps:

  1. Check are your images not null when you assign them meetingIconImageView.

  2. Check are images visible in built in UIImageView in UITableViewCell (cell.imageView.image = UIImage...).

  3. Check is meetingIconImageView actually visible in view - set red background. Maybe constrains are messed up.

  4. Check are you doing something wrong in your custom cell - maybe outlet is wrongly connected or you're doing something crazy in init method.

If still wrong then take a beer and check it tomorrow morning ;-)

Upvotes: 1

Moriya
Moriya

Reputation: 7906

There is nothing specific wrong with your code as far as I can see but here are some things to try

Set a breakpoint and make sure that UIImage constructor returns an image and not just nil.

if it's nil:

  • Check that the images are added to the project properly and that it's named as you expect.

  • Check that the image has a target set to the projects target. Sometimes the images gets added incorrectly and is not really part of what gets built when you actually run the app. Adding them to Images.xcassets instead of just loosely in the project might fix this in an easy way.

if it's not nil:

  • Check that your imageView has a proper frame set. You can view it in the Debug View Hierarchy function as your app is running. Trying to set the constraints to a fixed size as a test might help you find any issues related to this.

On another note you really shouldn't need to do

cell.setNeedsLayout()
cell.setNeedsDisplay()

Upvotes: 1

Related Questions