你好吗?
我想在每次调用计时器时创建一个新的实例变量,例如
numberofObjects += 1;
i = numberofObjects;
UIImageView *Object[i] = [[UIImageView alloc] initWithFrame:CGRectMake(randomx,0,36 ,36)];
UIImage *imag = [UIImage imageNamed:@"ball.png"];
[Object[i] setImage:imag];
[self.view addSubview:Object[i]];
有办法做到这一点吗?
任何意见将不胜感激。
答案 0 :(得分:2)
这并不难做到。我假设您将只有最大数量的UIImageViews,因为这会增加很多开销,如果允许永久继续,您可能会遇到问题。在.h文件中,
@interface viewController : UIViewController {
int numberAdded;
NSTimer * timer;
UIImageView * currentImageView;
NSMutableArray * arrayOfImageViews;
}
- (void)addNewImageView;
@end
在.m文件中:
#define MaxImageViews 20 // This is changeable!
@implementation viewController
- (void)viewDidLoad; {
[super viewDidLoad];
numberAdded = 0;
arrayOfImageViews = [[NSMutableArray alloc] init];
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(addNewImageView) userInfo:nil repeats:YES];
}
- (void)addNewImageView; {
if(numberAdded >= MaxImageViews){
[timer invalidate];
timer = nil;
return;
}
int randomX = arc4random() % 320; // Gives value from 0 - 319.
int randomY = arc4random() % 480; // Gives value from 0 - 479.
UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(randomX, randomY, 36, 36)];
imageView.image = [UIImage imageNamed:@"ball.png"];
[self.view addSubview:imageView];
[arrayOfImageViews addObject:imageView];
[currentImageView release];
currentImageView = imageView;
}
- (void)dealloc; {
[currentImageView release];
[arrayOfImageViews release];
[super dealloc];
}
@end
这应该跟踪数组arrayOfImageViews
中的所有imageView,并且您可以通过调用[arrayOfImageViews objectAtIndex:i]
来访问第i个imageView。 currentImageView
指针跟踪添加的最新UIImageView。希望有所帮助!
答案 1 :(得分:0)
将图像视图的指针存储在NSMutableArray对象中。