代码之家  ›  专栏  ›  技术社区  ›  Cole

UIView显示在UITableView部分,滚动时从未添加到该部分

  •  2
  • Cole  · 技术社区  · 16 年前

    [cell.contentView addSubview:self.overallCommentViewContainer];
    

    当我快速向上/向下滚动时,UIView出现在第0节中,尽管我从未将UIView添加到第0节中的任何单元格中。

    下面是我的 cellForRowAtIndexPath

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *kCustomCellID = @"CustomCellID";
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCustomCellID];
        if (cell == nil)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kCustomCellID] autorelease];
        }
    
        // Configure the cell.
        switch(indexPath.section) {
    
            case 0: 
                // other code
                break;
            case 1:  
    
                // add the overall comment view container to the cell
                NLog(@"adding the overallCommentViewContainer");
                [cell.contentView addSubview:self.overallCommentViewContainer];
                NLog(@"creating the row at: Section %d, Row %d", indexPath.section, indexPath.row);
                break;
        }
        return cell;
    }
    
    1 回复  |  直到 16 年前
        1
  •  3
  •   Adam Alexander    16 年前

    如果UITableView的单元格已准备好重用,则其dequeueReusableCellWithIdentifier方法将很高兴地返回最初在第1节中使用的第0节的单元格!我向您推荐这样的东西,让它们分开:

    UITableViewCell *cell;
    
    // Configure the cell.
    switch(indexPath.section) {
    
        case 0: 
            cell = [tableView dequeueReusableCellWithIdentifier:@"Section0Cell"];
            if (cell == nil) {
                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Section0Cell"] autorelease];
            }
            // other code
            break;
        case 1:  
            cell = [tableView dequeueReusableCellWithIdentifier:@"Section1Cell"];
            if (cell == nil) {
                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Section1Cell"] autorelease];
                // add the overall comment view container to the cell
                NLog(@"adding the overallCommentViewContainer");
                [cell.contentView addSubview:self.overallCommentViewContainer];
            }
            NLog(@"creating the row at: Section %d, Row %d", indexPath.section, indexPath.row);
            break;
    }
    return cell;
    

    关键是要为正在使用的每种类型的单元格使用不同的标识符字符串,该字符串不能与表中的其他单元格互换。

    推荐文章