开发者

UIView showing up in a UITableView section it was never added to when scrolling

I've got a UIView that I'm adding to a cell's content view in a particular section (Section 1 specifically), as shown below:

[cell.contentView addSubview:self.overallCommentViewContainer];

When I quickly scroll up/down - the UIView appears in Section 0 - even though I 开发者_StackOverflow社区never added the UIView to any of the cell's in Section 0.

Here's a detailed look at my cellForRowAtIndexPath method:

- (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;
}


if the UITableView has cells ready for reuse, its dequeueReusableCellWithIdentifier method will happily return a cell for section 0 that was originally used in section 1! I'd recommend something like this for you to keep them separate:

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;

The key is to use a different identifier string for each type of cell you're using that is not interchangeable with other cells in the table.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜