正在动态添加UIImageView



在我的应用程序中,我正在使用UIImageViews,我想通过使用名为imageView0、imageView1、imageView2的for循环来动态创建它……

我的代码如下

 for(i=0;i<number;i++)
{
        scrollViewImageToDrag = [[UIImageView alloc] initWithImage:image];
//        NSString *imageViewnameStr = [NSString stringWithFormat:@"scrollViewImageToDrag%d",i];
}

在执行for循环后,它应该创建次数为(例如10)的UIImageViews,其系列名称如imageView0、imageView1、imageView2……

我怎样才能做到这一点。

创建UIImageView时。。将他们的标签设置在一个范围内,比如(10-20)

所以。像这样初始化你的ImageView。。

 for (int i=0; i< 20; i++) {
UIImageView *ImageView = [[UIImageView alloc] init] ;
// ImageView formatting code here...
ImageView.tag = i+20;
   }

然后,当你想进行上面的循环(你在问题中给出的)时,得到你的UIImageView。。

for (int i=0; i< 20; i++) {
UIImageView *ImageView = (UIImageView *)[self.view viewWithTag:i+20]; // get the ImageView with tag
}

这就是解决方案。。您不能将文本重命名为变量并使用其函数

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

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)。

 NSInteger x = y = 5;
 for(NSInteger i = 0; i < 10; i++)
 {
    UIImage *image = [UIIimage imageNamed:[NSString stringWithFormat:@"imageView%d",i]];
    UIImageView *imageView = [UIImageView alloc] init];
    [imageView setFrame:CGRectMake(x,y,45,45)];
    [imageView setImage:image];
    [imageView setTag:i];
    [yourScrollView addSubView:imageView];
    //If you want to access your ImageView by tapping
    UITapGestureRecognizer *singleTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageSelect:)];
    singleTap.numberOfTapsRequired=1;
    [imageView addGestureViewRecognizer:singleTap];
    image=nil;
    if(i%4==0) {
      x=0;
      y=y+50;
    } else {
     x=x+50;
   }
 }
 - (IBAction)imageSelect:(UITapGestureRecognizer *)sender {
       UIImageView *imageView=(UIImageView *)sender.view;
      //Here you can access above imageView
}

祝你好运!

最新更新