如何以编程方式将多个图像添加到uitableviewcell

时间:2014-10-16 13:29:51

标签: ios uitableview

如何以编程方式将多个图像添加到uitableviewcell。

案例是第一个单元格可能包含两个图像,第二个单元格可能包含1,2,3或4.等等。表格单元格中的最大图像数量为5。

我的代码是

在ViewDidLoad

imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 100, 300, 300)];
imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 100, 300, 140)];
imageView3 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 260, 300, 140)];
imageView4 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 260, 150, 140)];
imageView5 = [[UIImageView alloc] initWithFrame:CGRectMake(160, 260, 150, 140)];
imageView6 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 100, 150, 140)];
imageView7 = [[UIImageView alloc] initWithFrame:CGRectMake(160, 100, 150, 140)];


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CellIdentifier";

    UITableViewCell   *image_cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (image_cell==nil)
    {
        image_cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    }

        if (sub_image_array.count==1)
            {
            [image_cell.contentView addSubview:imageView1];
            }

        else if (sub_image_array.count==2)
        {
            [image_cell.contentView addSubview:imageView2];

            [image_cell.contentView addSubview:imageView3];

        }
        else if (sub_image_array.count==3)
        {
           [image_cell.contentView addSubview:imageView2];
           [image_cell.contentView addSubview:imageView4];
            [image_cell.contentView addSubview:imageView5];

        }
        else if (sub_image_array.count==4)
        {
            [image_cell.contentView addSubview:imageView6];
            [image_cell.contentView addSubview:imageView7];
            [image_cell.contentView addSubview:imageView4];
            [image_cell.contentView addSubview:imageView5];

        }
    return image_cell;
}

1 个答案:

答案 0 :(得分:1)

您的代码存在几个关键问题。

  1. 细胞被重复使用。在使用时,您会不断地向每个单元格添加图像视图。在重新使用单元格之前,您需要删除可能之前添加的现有图像视图。
  2. 视图只能有一个父视图。您无法预先分配一组固定的图像视图,然后尝试将每个图像视图添加到多个单元格。摆脱七个预建的图像视图。而是根据需要为每个单元格创建图像视图。
  3. 最好的方法是创建一个传递图像数组的自定义表视图单元类。然后,单元格根据需要负责设置自己的图像视图。这将所有逻辑放在它所属的单元类中,而不是将那个讨厌的逻辑放在视图控制器中。