将子视图添加到UITableViewCell:滚动时添加了几次

Bla*_*use 1 iphone xcode uitableview ios

我的tableView中有一些不同的单元格,每个单元格都有不同的子视图.每当一个单元格消失并重新出现时,子视图就会在旧视图的顶部添加,也会添加到其他单元格中.在不使用自定义单元格的情况下向单元格添加子视图的正确方法是什么?

提前致谢

- (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....
Run Code Online (Sandbox Code Playgroud)

Saa*_*aad 5

每当你滚动单元格的行方法被调用时,所以当你的单元格可见时,它会将子视图添加到单元格,放置一个已添加视图的检查,制作一个ivar,即bool,当你添加视图时将其设置为true当你像这样卸妆时,你是假的

.
.
.

 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;

    }

.
.
.
Run Code Online (Sandbox Code Playgroud)