For an iPhone app I am developing I need to assign custom uitableviewcell images based on the integers of arbitrary items in an array. I noticed while doing some testing that indexPath of row only returns indices for the view shown, so basically I need to know how to take an array, of arbitrary size, let’s say right now it has 10 items, and those 10 items are in a table, each item a cell, I need each item to have an index like item 1 is index 0, item 2 is index 1 and so on. So my code would read, if the index == 0, then display this image in the cell, if the index != 0 then display another. I tried that but like I said if I scrolled to the bottom of my tableview it would reassign whichever table item is at the top of the view to 0, so as I scrolled the images kept changing. So basically i need help assigning the images based on an index in my array rather than on the index of the table.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = @"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MyIdentifier] autorelease];
}
cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.detailTextLabel.numberOfLines = 1;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
NSString *title =[[stories objectAtIndex: indexPath.row] objectForKey: @"summary"];
NSString *title2 =[[stories objectAtIndex: indexPath.row] objectForKey: @"title"];
NSString *dayOfMonthString = [title substringWithRange: NSMakeRange(2, 2)];
int dateChooser = [dayOfMonthString intValue];
NSString *monthString = [title substringWithRange: NSMakeRange(0, 2)];
int monthChooser = [monthString intValue];
cell.textLabel.text =title2;
cell.imageView.image =
[UIImage imageNamed: [NSString stringWithFormat: @"cal%d.png", dateChooser]];
if (monthChooser == 1 && (INDEX COMPARISON CODE???){
UIImageView *myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Jan1.png"]];
[cell setBackgroundView:myImageView];
}
Your problem is not getting the right index for the right cell. The
rowproperty of theindexPathdo correspond to the index of the cell in the whole list of cells, not the index of the visible cells only, so exactly as you expected initially.I bet your problem is that you don’t use the reuse mechanism of UITableViewCells correctly
.
When you scroll in your TableView,
UITableViewCellsthat are not on screen anymore are “recycled” and reused to display new cells onscreen, in order to avoid too much allocations and useless initializations that would else slow down the scrolling of your tableView.The correct code pattern for returning a cell is the following: