Question

I am developing an app, that takes events from 3 different shared calendars, and show them, sorted by date, in a UITableView. first calendar is for "Sports Shown on TV" second calendar is for "Live Music on Stage" third calendar is for fixed events (like every thursday is "ladies night")

I would like to show a small image on the cell, and the image needs to change according to the event. The way I do it now is to just write the image filename in the event description, and use that to set the image.

cell.imageView.image = [UIImage imageNamed:[entry valueForKeyPath:@"content.$t"]];

What i would like to do was to set the image according to either the calendar name, or maybe the contents of the event title

I tried

NSArray *gdWho = entry[@"gd$who"];
NSString *calendar = gdWho[0][@"valueString"];
if([calendar isEqualToString:@"Live Music on Stage"])
{
    cell.imageView.image = [UIImage imageNamed:@"music-notes-40x40.jpg"];
}

and it works, but as soon as i scroll the tables they get mixed up. I read somewhere that this is an expected outcome, as the cells indexpath change when scrolling, thus rendering my code unusable.

But how would you do it then. Could anyone point me in the right direction - I would really like to able to put an image of the artist playing live on stage, so my optimal solution would be to display an image if the NSString = [entry valueForKeyPath:@"title.$t"] contained for example the name "dennis"

Was it helpful?

Solution

it works, but as soon as i scroll the tables they get mixed up

This indicates a problem with UITableViewCell "recycling". You need to change the code of your tableview:cellforrowatindexpath: in such a way that it sets cell.imageView.image unconditionally, not only when the cell is created for the first time.

In addition, you could replace the chain of if statements that check the calendar for various specific values with a lookup in a dictionary, like this:

// This code goes into your viewDidLoad method. imageForCalendarType is an ivar
imageForCalendarType = @{
    @"Live Music on Stage" : [UIImage imageNamed:@"music-notes-40x40.jpg"]
,   @"Sports Shown on TV"  : [UIImage imageNamed:@"sport-tv-40x40.jpg"]
,   @"Fixed Event"         : [UIImage imageNamed:@"fixed-40x40.jpg"]
};

Now you can use the image from the dictionary, like this:

// This goes into your tableview:cellforrowatindexpath: method
cell.imageView.image = imageForCalendarType[calendar];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top