Iphone 动态添加UIImageView

Iphone 动态添加UIImageView,iphone,ios,Iphone,Ios,在我的应用程序中,我使用UIImageViews,我希望通过使用名为imageView0、imageView1、imageView2的for循环动态创建UIImageViews 我的代码如下 for(i=0;i<number;i++) { scrollViewImageToDrag = [[UIImageView alloc] initWithImage:image]; // NSString *imageViewnameStr = [NSString s

在我的应用程序中,我使用UIImageViews,我希望通过使用名为imageView0、imageView1、imageView2的for循环动态创建UIImageViews

我的代码如下

 for(i=0;i<number;i++)
{

        scrollViewImageToDrag = [[UIImageView alloc] initWithImage:image];
//        NSString *imageViewnameStr = [NSString stringWithFormat:@"scrollViewImageToDrag%d",i];

}
在执行for循环后,它应该创建10次UIImageView的数字示例,并使用系列名称,如imageView0、imageView1、imageView2


如何实现这一点。

不可能实现您想要的,但如果您想区分图像视图,可以使用标记属性

for (int i=0; i<[getEffectsImageData count]; i++)
{
    //Your code here.....

    imageViewsArray.tag = i ;// This would become your first image. and you can differentiate from tag.

}

与Objective-C中的许多解释器语言不同,您不能按照建议动态创建对象名称。您可以改用数组

NSMutableArray scrollViewImagesArray = [[NSMutableArray alloc] initWithCapacity:number];
 for(i=0;i<number;i++)
{
UIImageView *myNewImageView = [[UIImageView alloc] initWithImage:image];
[myImageView retain]; //With ARC you would not need this statement, you directly call this
myImageView.tag = i; //This may come handy to identify the images if you to not want to use
                     //or do not need to. In a table view controller you may not need that array for images in a table cell. 
[scrollViewImagesArray addObject:myNewImageView];

}

//稍后,当您不再需要这些图像时,为了不忘记删除所有对象并释放aray,除非您使用ARC,那么将nil指定给阵列就可以了

创建UIImageView时。。将标签设置在10到20之间

所以。 像这样初始化ImageView

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

UIImageView *ImageView = [[UIImageView alloc] init] ;
// ImageView formatting code here...

ImageView.tag = i+20;
   }
for (int i=0; i< 20; i++) {

UIImageView *ImageView = (UIImageView *)[self.view viewWithTag:i+20]; // get the ImageView with tag
}
然后,当你想让你在问题中给出的上述循环得到你的UIImageView时,像这样

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

UIImageView *ImageView = [[UIImageView alloc] init] ;
// ImageView formatting code here...

ImageView.tag = i+20;
   }
for (int i=0; i< 20; i++) {

UIImageView *ImageView = (UIImageView *)[self.view viewWithTag:i+20]; // get the ImageView with tag
}
这就是解决办法。。 不能将文本重命名为变量并使用其函数


祝你好运

@AlexTerente[UIImageView new]与[[UIImageView alloc]init]相同,只是标题和描述问题的方式有所改变。基本问题仍然是相同的,但您在UIImageView上调用init的操作没有正确初始化。我看到您已经编辑了代码,并且在文档中找到了–initWithImage:Method,您必须使用NSMutableArray或类似的方法。你想要的方式根本行不通。