如何以编程方式将多个图像添加到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;
}
答案 0 :(得分:1)
您的代码存在几个关键问题。
最好的方法是创建一个传递图像数组的自定义表视图单元类。然后,单元格根据需要负责设置自己的图像视图。这将所有逻辑放在它所属的单元类中,而不是将那个讨厌的逻辑放在视图控制器中。