Ranjeet Sajwan
Ranjeet Sajwan

Reputation: 1921

Problem with table view in iPhone when adding image to it

i have following code to create cell and add image to it

UIImageView* MyImage =[[UIImageView alloc]initWithFrame:CGRectMake(100,10,40,40)];  
[MyImage setImage:[UIImage imageNamed:[imageArray objectAtIndex:indexPath.row]]];  
[MyImage setBackgroundColor:[UIColor clearColor]];  
[cell addSubview:MyImage];  
[MyImage release];  

cell.textLabel.text=[dataArray objectAtIndex:indexPath.row];  
     return cell;

I am using this table for many purposes and therefore refreshing it again and again.... Therefore next i age overlaps the last one due to which problem occurs and both of these images are visible(i am using transparent background for each image).... other problem occurs when i need no image..here i am unable to remove the last image ...

please help

Upvotes: 0

Views: 674

Answers (2)

Sanniv
Sanniv

Reputation: 1877

As you might be aware that when you reuse cell from 'dequeueReusableCellWithIdentifier', it returns you existing cell instance if present, that means if cell exist its data also exists i.e. image, so you need to clear the old image before updating the cell with new data as if new data doesn't have image then it will show old image, I guess you got the point...

Ok here is the solution:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell==nil)
{
   cell = [[UITableViewCell alloc] initWithStyle:UITableViewStyleDefault reuseIdentifier:cellIdentifier];

   UIImageView* MyImage =[[UIImageView alloc]initWithFrame:CGRectMake(100,10,40,40)]; 
   MyImage.tag = 1000; 

   [MyImage setBackgroundColor:[UIColor clearColor]];  
   [cell addSubview:MyImage];  
   [MyImage release]; 
}
UIImageView *imgView = (UIImageView*)[cell viewWithTag:1000];
imgView.image = nil;
imgView.image = [UIImage imageNamed:[imageArray objectAtIndex:indexPath.row]];

Upvotes: 3

Ishu
Ishu

Reputation: 12787

Where you use

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"MyIdentifier"] autorelease]; }

Modify this to UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"]; cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"MyIdentifier"] autorelease];

This one is the solution it always add new frame to old existing cell.

Or

Remove background color to some color from clear color and each time add on image either default image or particular image.same for label when you dont want to add any text to label then also add text=@"";

Upvotes: 0

Related Questions