Reputation: 569
Is there a better way to load images dynamically into the tableviewcell for different rows other than using the if statements? What if I have a lot of cells. does that mean I would have to write a lot of if statements? Also is there a way to retrieve an image from core data and use it as a image for tableview cell? thanks in advance.
- (UIImage *)imageForMagnitude:(CGFloat)magnitude {
if (magnitude >= 5.0) {
return [UIImage imageNamed:@"5.0.png"];
}
if (magnitude >= 4.0) {
return [UIImage imageNamed:@"4.0.png"];
}
if (magnitude >= 3.0) {
return [UIImage imageNamed:@"3.0.png"];
}
if (magnitude >= 2.0) {
return [UIImage imageNamed:@"2.0.png"];
}
return nil;
}
edit: what if it isn't about magnitude? for example a list of products or like the app store on the iphones. how did they manage to generate different images for the different apps on the table? are they using a table or is there a better way to do this?
Upvotes: 1
Views: 272
Reputation: 163248
Round down the magnitude using the floorf
function from <math.h>
Then use the MIN
and MAX
macros to protect the real value from going above 5 or below 2.
int realMagnitude = (int) MAX(MIN(floorf(magnitude), 5.0f), 2.0f);
return [UIImage imageNamed:[NSString stringWithFormat:@"%d.0.png", realMagnitude]];
Update: I think this is what you're looking for: in -tableView:cellForRowAtIndexPath:
, use the provided NSIndexPath
to fetch the relevant image:
cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg", indexPath.row]];
Upvotes: 0
Reputation:
Hmm maybe a switch statement. Or you could just round the magnitude off and then..
[NSString stringWithFormat:@"%d.0.png", newMagnitude];
Upvotes: 1