在我的应用程序中使用UIImageViews,我想通过使用名称为imageView0,imageView1,imageView2 .......
的for循环动态创建我的代码如下
for(i=0;i<number;i++)
{
scrollViewImageToDrag = [[UIImageView alloc] initWithImage:image];
// NSString *imageViewnameStr = [NSString stringWithFormat:@"scrollViewImageToDrag%d",i];
}
执行for循环后,它应该创建具有系列名称的UIImageViews的数字(例子10),如imageView0,imageView1,imageView2 .......
我怎样才能实现这一点。
答案 0 :(得分:4)
当你创建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
}
这是解决方案.. 您无法将文字重命名为变量并使用其功能
答案 1 :(得分:0)
无法实现您想要的效果,但如果您想区分图像视图,则可以使用标记属性。
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.
}
答案 2 :(得分:0)
与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分配给数组应该这样做)。
答案 3 :(得分:0)
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
}
祝你好运!