EDIT: Actually images appear fine, it’s when I scroll that they get mixed up…
I’m parsing an XML file with links to images which I’m putting into a UITable. For some reason the pictures are getting completely mixed up and when I scroll down the table some of them even start to change! Here’s the code I’m using for my UITable:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
Tweet *currentTweet = [[xmlParser tweets] objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
CGRect imageFrame = CGRectMake(2, 8, 40, 40);
customImage = [[UIImageView alloc] initWithFrame:imageFrame];
[cell.contentView addSubview:customImage];
}
NSString *picURL = [currentTweet pic];
if (![picURL hasPrefix:@"http:"]) {
picURL = [@"http:" stringByAppendingString:picURL];
}
customImage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:picURL]]];
return cell;
}
Any idea what I’m doing wrong?
Any help is seriously appreciated. Thx!
Your problem is that if the cell is not
nil(i.e. you’ve successfully reused a cell that has scrolled off the screen), you’re not setting thecustomImagepointer properly (since it is a class instance variable, it has the value from the last cell it created). So, define some non-zero constant forkCustomImageTagand then modify theifstatement incellForRowAtIndexPathto be:Set the
tagwhen you createcustomImageand use thattagto retrieve an existingcustomImagein the reusedUITableViewCell.