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

Ios 如何以编程方式将多个图像添加到uitableviewcell,ios,uitableview,Ios,Uitableview,如何以编程方式将多个图像添加到uitableviewcell 情况是,第一个单元格可能包含两个图像,第二个单元格可能包含1、2、3或4。等tableviewcell中的最大图像数为5 我的代码是 在ViewDidLoad中 imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 100, 300, 300)]; imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake

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

情况是,第一个单元格可能包含两个图像,第二个单元格可能包含1、2、3或4。等tableviewcell中的最大图像数为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;
}

您的代码有几个关键问题

  • 细胞被重新利用。在使用每个单元格时,您会不断地向其添加图像视图。在重用单元格之前,需要删除先前添加的图像视图和现有图像视图
  • 视图只能有一个父视图。不能预先分配一组固定的图像视图,然后尝试将每个视图添加到多个单元格中。去掉七个预构建的图像视图。而是根据需要为每个单元格创建图像视图

  • 最好的方法是创建自己的自定义表视图单元类,并将其传递给图像数组。然后,单元会根据需要设置自己的图像视图。这会将所有逻辑放在它所属的单元格类中,而不是将那个讨厌的逻辑放在视图控制器中。

    您是否实现了
    cellforrowatinex
    方法并尝试在其中添加多个图像视图?是的,我实现了cellforrowatinex,然后问题出在哪里?您可以在其中添加任意数量的图像视图?如何显示图像,垂直还是水平?您需要创建子类
    UITableViewCell
    并创建一个自定义单元格。在其中添加图像如果希望图像以垂直布局显示,您还需要管理单元格高度。我的问题是在滚动tableview时图像正在更改