UIImageView仅在Uitableviewcell中附加偶数行

时间:2013-07-16 18:54:05

标签: uitableview uiimageview uiimage

我使用uiimage创建uitableview自定义单元格我想只为偶数行添加一个图像,但它在这里不起作用是代码

     UITableViewCell *cell;
        UILabel *label = nil;

        cell = [tv dequeueReusableCellWithIdentifier:@"Cell"];
        if (cell == nil)
        {
    //label information
    }
       NSString *text = [items objectAtIndex:[indexPath row]];


     UIView *selectionView = [[UIView alloc]initWithFrame:cell.bounds];
        [selectionView setBackgroundColor:[UIColor colorWithRed:0 green:1 blue:1 alpha:1]];
        cell.selectedBackgroundView = selectionView;


    if (indexPath.row % 2==0) {

            UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(128,5, 32, 32)];
            imv.image=[UIImage imageNamed:@"England.png"];
            [cell.contentView addSubview:img];
            [imv release];

        }
        else {

           //  ....

        }
 return cell;

在第3行之后,如果我尝试滚动所有行有一个图像,则所有行都会将此图像作为所有行

1 个答案:

答案 0 :(得分:0)

正在重用您的单元格,并且在重用单元格时不会删除UIImageView。在else语句中,您需要添加代码以使用图像删除UIImageView。现在,看起来您没有保留对UIImageView的引用,因此您不能只调用removeFromSuperview。在else语句中,您可以尝试枚举cell.contentView的所有子视图并删除任何UIImageView:

for (UIView *theSubview in [cell.contentView subviews])
{
    if(theSubview isKindOfClass:[UIImageView class])
    {
        [theSubview removeFromSuperview];
    }
 }

请注意,我尚未测试此代码。