C.Wetherell
C.Wetherell

Reputation: 215

How display random Image in UIImageView Each time it resets

I'm currently making a game. I have an UIImageView that scrolls from right to left and once it leaves the ViewController the image resets on the right and scrolls left again, this currently set to displays "image1" I would like to change it to display a different image randomly from a set of 5 each time it resets to the right.

Here is my Method:

- (void)PlacePipe{

    RandomTopPipePosition = arc4random() %350;
    RandomTopPipePosition = RandomTopPipePosition - 228;
    RandomBottomPipePosition = RandomTopPipePosition + 660;

    PipeTop.center = CGPointMake(340-10, RandomTopPipePosition);
    randomImagebottom.center = CGPointMake(340-10, RandomBottomPipePosition);

}

The name of the images I want to randomly add into this UIImageView are -toppipestyleone.png, toppipestyletwo.png, toppipestylethree.png, toppipestylefour.png, toppipestylefive.png".

I'm not sure at the best route to doing this, I looked at doing it with an array but I'm not sure how to set up an array or even call images randomly.

Upvotes: 0

Views: 1438

Answers (1)

Lyndsey Scott
Lyndsey Scott

Reputation: 37290

You could put the image names in an array as you considered, ex.

NSArray *imageNameArray = [[NSArray alloc] initWithObjects:@"toppipestyleone.png", @"toppipestyletwo.png", @"toppipestylethree.png", @"toppipestylefour.png", @"toppipestylefive.png", nil];

then create and set an image using the image name at a random index of that array using:

imageView.image = [UIImage imageNamed:[imageNameArray objectAtIndex:arc4random_uniform((uint32_t)[imageNameArray count])];

Upvotes: 4

Related Questions