mano
mano

Reputation: 3

problem with subviews of uitableviewcell

I added a subviews to uitableviewcells its working fine, but when I scroll up or down subviews are adding multiple times. I donno where I am wrong.

Here is my code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

 static NSString *CellIdentifier = @"MainPageCellView";
 MainPageTableCellView *cell = (MainPageTableCellView *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

 if (cell == nil) {  
  [[NSBundle mainBundle] loadNibNamed:@"MainPageTableCellView" owner:self options:nil];  
  cell = mainPageTableCell;
 } 



 [cell setNameText:[namesArray objectAtIndex:indexPath.row]];
 [cell setPositionText:[positionArray objectAtIndex:indexPath.row]];
 [cell setCompanyNameText:[companyNameArray objectAtIndex:indexPath.row]];
 [cell setDistanceText:[distArray objectAtIndex:indexPath.row]];
 [cell setImageViewImage:[imagesArray objectAtIndex:indexPath.row]];


 UIImage *halo = [UIImage imageNamed:@"h1.png"]; 
 UIImageView *haloV = [[UIImageView alloc] initWithImage:halo];

 if(indexPath.row == 0)
 [cell addSubview: haloV];
 else if(indexPath.row ==2)
 [cell addSubview: haloV];
 else if(indexPath.row ==3)
 [cell addSubview: haloV];


 return cell;

}

Upvotes: 0

Views: 450

Answers (1)

Ken Pespisa
Ken Pespisa

Reputation: 22284

You are adding subviews to the cells whether or not they have just been created or they are being reused. When you scroll up and down, they get reused, and thus the subviews get added repeatedly.

Move the calls to addSubview within the if (cell==nil) block and that should fix the problem.

 if (cell == nil) {  
   [[NSBundle mainBundle] loadNibNamed:@"MainPageTableCellView" owner:self options:nil];  
   cell = mainPageTableCell;

   UIImage *halo = [UIImage imageNamed:@"h1.png"]; 
   UIImageView *haloV = [[UIImageView alloc] initWithImage:halo];

   if(indexPath.row == 0)
     [cell addSubview: haloV];
   else if(indexPath.row ==2)
     [cell addSubview: haloV];
   else if(indexPath.row ==3)
     [cell addSubview: haloV];
 } 

Upvotes: 1

Related Questions