2014-10-16 102 views
-1

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

的情况是第一单元可包含两个图像时,第二可包含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; 
} 
+0

您是否实现了'CellForRowAtIndex'方法并尝试在其中添加多个imageViews? – 2014-10-16 13:33:22

+0

是的,我实现了CellForRowAtIndex – 2014-10-16 13:36:31

+0

那么问题在哪里?你可以根据需要添加尽可能多的imageViews? – 2014-10-16 13:37:12

回答

1

您的代码有几个关键问题。

  1. 单元格被重用。您一直使用的图像视图反复添加到每个单元格。在重新使用单元格之前,您需要删除以前可能已添加的现有图像视图。
  2. 视图只能有一个父视图。您不能预先分配一组固定的图像视图,然后尝试将每个视图添加到多个单元格。摆脱你的七个预建图像视图。相反,根据需要为每个单元格创建图像视图。

最好的方法是创建您自己的传递图像数组的自定义表格视图单元类。然后,细胞照顾根据需要设置自己的图像视图。这将所有的逻辑放在它所属的单元类中,而不是将视觉控制器中令人讨厌的逻辑放入。

相关问题