2012-03-21 126 views
0

我有一个自定义单元格的tableView,我的第一个单元格与其他单元格不同。 (它包含一个小图像和一个标签)。我做这样的:UITableView和自定义单元格

pragma mark - tableView data source methods 
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 


    SuggestionCarteCell *cell = (SuggestionCarteCell *)[tableView dequeueReusableCellWithIdentifier:@"carteCell"]; 
    if (cell == nil) { 
     NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SuggestionCarteCell" owner:nil options:nil] ; 
     cell = [nib objectAtIndex:0]; 
    } 

    if (indexPath.row == 0) { 
     // crer l'image 

     NSLog(@" je suis dans row 0"); 
     UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(21, 9, 13, 26)]; 
     imageView.image = [UIImage imageNamed:@"iconeLocation"]; 
     [cell addSubview:imageView]; 
     cell.labelRegion.frame = CGRectMake(21+13+10, cell.labelRegion.frame.origin.y,cell.labelRegion.frame.size.width , cell.labelRegion.frame.size.height); 
     cell.labelRegion.text = [NSString stringWithFormat:@"A proximité,"]; 

    } 
    else{ 
    Region *region = [Region new]; 
    region =(Region *) [arrayRegion objectAtIndex:indexPath.row]; 
    cell.labelRegion.text =region.nomRegion; 


    } 
    return cell; 
} 
在第一时间它的好

,但是当我滚动我的第一个单元格(小图片加)出现在其他行。我做错了什么?谢谢

回答

1

您有两种类型的单元格,但只有一个重用标识符。

两个选项:

  • 确保当你的电池重复使用它的状态重置为默认的,空的状态。有一个用于此目的的prepareForReuse方法
  • 定义两个不同的单元格,每个单元格都有其自己的唯一重用标识符。这样,你的第一个,不同的细胞将不会以后
+0

我选择了第二个解决方案,两个自定义单元格。谢谢 – samir 2012-03-21 15:22:04

0

重用尝试这样

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


SuggestionCarteCell *cell = (SuggestionCarteCell *)[tableView dequeueReusableCellWithIdentifier:@"carteCell"]; 
UIImageView *imageView; 
if (cell == nil) { 
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SuggestionCarteCell" owner:nil options:nil] ; 
    cell = [nib objectAtIndex:0]; 
    imageView = [[UIImageView alloc]initWithFrame:CGRectMake(21, 9, 13, 26)]; 
    imageView.tag = 100; 
    [cell addSubview:imageView]; 
} else { 
    imageView = [cell viewWithTag:100]; 
} 

if (indexPath.row == 0) { 
    // crer l'image 

    NSLog(@" je suis dans row 0"); 

    imageView.image = [UIImage imageNamed:@"iconeLocation"]; 

    cell.labelRegion.frame = CGRectMake(21+13+10, cell.labelRegion.frame.origin.y,cell.labelRegion.frame.size.width , cell.labelRegion.frame.size.height); 
    cell.labelRegion.text = [NSString stringWithFormat:@"A proximité,"]; 

} 
else{ 
    Region *region = [Region new]; 
    region =(Region *) [arrayRegion objectAtIndex:indexPath.row]; 
    cell.labelRegion.text =region.nomRegion; 
    imageView.image = nil; 
} 
return cell; 

}

这种方式,细胞被重用,仅创建一次图像视图,那么你可以通过它的标签获得它的参考,但是在一种情况下,你设置了它的图像,在另一种情况下,你将它设置为零。