使用for loop -objective c动态添加图像

时间:2012-05-04 10:14:36

标签: iphone objective-c nsstring

我使用下面的代码在单个单元格内容视图中添加图像数量。

    cell.imageView1.image = [UIImage imageNamed:@"testImg1"];
            cell.imageView2.image = [UIImage imageNamed:@"testImg2"];
            cell.imageView3.image = [UIImage imageNamed:@"testImg3"];
            cell.imageView4.image = [UIImage imageNamed:@"testImg4"];
            cell.imageView5.image = [UIImage imageNamed:@"testImg5"];  
.............................  
............................  
cell.imageView20.image = [UIImage imageNamed:@"testImg20"];  

如何使用stringWithFormat循环使我的代码看起来像:

for(imageCounter = 1; imageCounter <21, imageCounter++)  
{  
cell.imageView(imageCounter).image = [UIImage imageNamed:@"testImg(imageCounter)"];  
}  

有任何建议吗?

4 个答案:

答案 0 :(得分:2)

要获得循环内部不同图像视图的引用,您必须将它们放在一个数组中或标记它们,而不是以前的方式:

  NSArray *cellImageViews;
  for(int imageCounter = 1; imageCounter < 21; imageCounter++)
  {
    [[cellImageViews objectAtIndex:imageCounter-1] setImage:[UIImage imageNamed:[NSString stringWithFormat:@"testImg%d", imageCounter]]];
  }

  for(int imageCounter = 1; imageCounter <21; imageCounter++)
  {
    [((UIImageView *)[cell viewWithTag:imageCounter]) setImage:[UIImage imageNamed:[NSString stringWithFormat:@"testImg%d", imageCounter]]];
  }

答案 1 :(得分:1)

UIImageView *img[20];//ur array of images

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

for (int i=0; i<20; i++) {

        //set frame  every time as ur requirement

        img[i].image = [UIImage imageNamed:[NSString stringWithFormat:@"testImg%d",i+1]];
        [cell.contentView addSubview:img[i]];
    }
}

我认为这段代码完美无缺 For More Examples以获得更好的描述。

答案 2 :(得分:1)

你使用了错误的逻辑。它不能像这样使用。而不是这个

for(imageCounter = 1; imageCounter <21, imageCounter++)
{
 cell.imageView(imageCounter).image = [UIImage imageNamed:@"testImg%d,(imageCounter)"];
}

您应该使用: -

yourImageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];

for(imageCounter = 1; imageCounter <21, imageCounter++)
{
 [yourImageView setImage:[UIImage imageNamed:@"testImg%d",imageCounter]];
 cell.imageView = yourImageView;
}

试试这个。希望它会帮助你谢谢你。)

答案 3 :(得分:1)

您好首先应将所有图像放在cellForRowAtIndexPath方法的数组中

NSMutableArray *imageArr=[[NSMutableArray alloc]initWithObject:cell.imageView1,cell.imageView2.....];

然后执行以下操作:

for(imageCounter = 1; imageCounter <21, imageCounter++) {



[imageArr objectAtindex:imageCounter].image = [UIImage imageNamed:[NSString stringwithformat:@"testImg%d", imageCounter]];
}

如果您需要任何澄清,请告诉我