cellForRowAtIndexPath中的ReusableCellWithIdentifier问题

时间:2012-05-10 14:01:17

标签: iphone uitableview

在我的应用程序中,我有一个imageView和一个UILabel。对于ImageView,我已经为它分配了asynch Image并且它工作正常,但是当我滚动表时,第一行和最后一行的标签重叠。

这是我的代码:

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

    productObject=[appDelegate.productArray objectAtIndex:indexPath.row];
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    UILabel *nameLabel;
    if (cell == nil) 
    {

        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero     reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;

    }   

    else 
    {

        AsyncImageView* oldImage = (AsyncImageView*)[cell.contentView viewWithTag:999];
        [oldImage removeFromSuperview];
    }

    CGRect nameLabelRect = CGRectMake(70,80,150,15);
    nameLabel = [[UILabel alloc] initWithFrame:nameLabelRect];    
    nameLabel.text = [NSString stringWithFormat:@"%@",productObject.productname];
    nameLabel.textAlignment = UITextAlignmentCenter;
    nameLabel.lineBreakMode = UILineBreakModeCharacterWrap;
    nameLabel.font = [UIFont boldSystemFontOfSize:15];
    nameLabel.backgroundColor = [UIColor clearColor];
    [cell.contentView addSubview: nameLabel];

    }

2 个答案:

答案 0 :(得分:7)

对于每个单元格使用单独的标识符,如下所示

 NSString *cellIdentifier = [NSString stringWithFormat:@"cell%i",indexpath.row];

或者只是不使用可重用性只是将单元格和数据放入其中

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

UITableViewCell *cell = [[UITableViewCell alloc]init];
UIButton *favBtn = [UIButton buttonWithType:UIButtonTypeCustom];
favBtn.frame = CGRectMake(0, 0, 50, 50);
favBtn.backgroundColor = [UIColor clearColor];
favBtn.showsTouchWhenHighlighted = YES;
favBtn.tag = indexPath.row;

UIButton *arrowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
arrowBtn.frame = CGRectMake(280, 26, 25, 25);
arrowBtn.backgroundColor = [UIColor clearColor];
arrowBtn.showsTouchWhenHighlighted = YES;
[arrowBtn setImage:[UIImage imageNamed:@"arrow.png"] forState:UIControlStateNormal];

UILabel *date = [[UILabel alloc]initWithFrame:CGRectMake(55, 26, 250, 25)];
date.font = [UIFont fontWithName:[[UIFont familyNames] objectAtIndex:0]  size:15];
date.text = ann.title;
date.textColor = [UIColor blackColor];
date.backgroundColor = [UIColor clearColor];

[cell.contentView addSubview:favBtn];
[cell.contentView addSubview:date];
[cell.contentView addSubview:arrowBtn];


    return cell;
}

我不是专家,但第二个为我工作的很好,希望你也好。

答案 1 :(得分:0)

您将nameLabel添加到单元格中,无论是新创建还是重用。所以是的,每当你将一个重复使用的单元格滚动到视图中时,它就会堆积在另一个标签上。