在for循环中增加UIImageView变量的数字部分?

时间:2010-09-10 13:06:46

标签: objective-c c xcode loops for-loop

我有三个名为myPicture1,myPicture2和myPicture3的UIImageView变量。在for循环中,我试图将myPicture末尾的数字增加1,以便我可以为三个变量中的每一个分配一个随机图像。以下是代码:

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

int g = arc4random() % 19;

NSString *imagename = [NSString stringWithFormat:@"image%d.jpg",g];

UIImage *picture = [UIImage imageNamed:imagename];

 UIImageView imageView = [[UIImageView alloc] initWithImage : picture];

 self.myPicture1 = imageView; **This is where I want myPicture to increase to myPicture 2 and then 3 **

}

这可能吗?

全心全意,

马丁

1 个答案:

答案 0 :(得分:1)

嗯,我认为你是以一种尴尬的方式接近这一点 可能最好的方法是将UIImageView存储在NSArray中。 所以在你的类声明中,而不是

@property (nonatomic, retain) UIImageView *myPicture1;
@property (nonatomic, retain) UIImageView *myPicture2;
@property (nonatomic, retain) UIImageView *myPicture3;

你会有

@property (nonatomic, retain) NSArray *myPictures;

然后你就像这样创建它们:

NSMutableArray *myTempArray = [NSMutableArray arrayWithCapacity:3];
for (i=0; i<3; i++)
{
    int g = arc4random() % 19;

    NSString *imagename = [NSString stringWithFormat:@"image%d.jpg",g];
    UIImage *picture = [UIImage imageNamed:imagename];

    UIImageView imageView = [[UIImageView alloc] initWithImage : picture];
    [myTempArray addObject: imageView];
    [imageView release];
}
self.myPictures = [NSArray arrayWithArray: myTempArray];