简体   繁体   中英

Add subview to UITableViewCell: Added several times when scrolling

I have some different cells in my tableView, each with different subviews. Each time a cell dissapear and reapear, the subview is addad on top of the old view, and also is added to other cells. What is the correct way to add subviews to cells without using custom cells?

Thanks in advance

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"StatisticsCell";

    StatisticsCell *cell = (StatisticsCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {        
        NSArray *topLevelObject = [[NSBundle mainBundle] loadNibNamed:@"StatisticsCell" owner:nil options:nil]; 
        for (id currentObject in topLevelObject)
        {
            if ([currentObject isKindOfClass:[UITableViewCell class]])
            {
                cell = (StatisticsCell *)currentObject; 



                break; 
            }
        }
    }


    if (indexPath.section == 0 && indexPath.row == 0)
    {
       //Add a subview here 
       [cell addsubview .... 
    }
    else if (indexPath.section == 0 && indexPath.row == 1)
    {
         //Add a subview here 
         [cell addsubview .... 
    }

     etc....

Whenever you scroll cell for row method is called, so when your cell be visible, it will add subview to the cell. Place a check that is view added already, make an ivar that is bool, and set it true when you add view, and false when you remove. Like this:

.
.
.

 if (indexPath.section == 0 && indexPath.row == 0 && isFirstViewAlreadyAdded== NO)
    {
       //Add a subview here 
       [cell addsubview .... 
       isFirstViewAlreadyAdded = YES;
    }
    else if (indexPath.section == 0 && indexPath.row == 1 && isSecondViewAlreadyAdded == NO)
    {
         //Add a subview here 
         [cell addsubview .... 
       isSecondViewAlreadyAdded = YES;

    }

.
.
.

You can check whether that subView is already added to cell or not.

UIView *subView = [tableCell viewWithTag:tagOfYourSubView];    
if (subView) {
     //subView exists
}
else {
     //subView does not exist
}

If it is not added then you can add.

Don't add the subview every time.. You should add the subview in the if(cell==nil) block. And after that you can set the hidden property as true or false according to indexpath.row. like:

if (indexpath.row == 0)
img1.hidden = FALSE;
else
img1.hidden = TRUE;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM