0

I'm trying to randomly display an image when my view loads. I don't want it to be from a UIButton, just whenever the view loads.

I've added the UIImage View to my View Controller http://bit.ly/1aopaMV and I've created a property for it.

@property (strong, nonatomic) IBOutlet UIImageView *imageView;

I'm not sure how to add images to the UIImage View and do it randomly.

Any help would be appreciated, I'm a total noob.

Thanks in advance.

Brandon Houlihan
  • 209
  • 1
  • 2
  • 6

2 Answers2

1

You could create an array of potential image names, determine a random number (like this: Generate random number in range in iOS?), then set the image property of the UIImageView.

All this could be placed in the viewDidLoad or viewWillDisplay: methods of your view controller.

There are, of course other approaches, but this would be fairly simple.

Community
  • 1
  • 1
picciano
  • 22,341
  • 9
  • 69
  • 82
  • I don't really understand how to do this. – Brandon Houlihan Jul 15 '13 at 20:32
  • basically what he is saying is have an array of known image names. When the view is about to appear on the screen, randomly generate a number which will indicate an index for the array of names. Once you have that index, retrieve the corresponding name, and now you have selected your random image. – MZimmerman6 Jul 15 '13 at 20:58
0

viewWillAppear:

NSArray *myImageArray = [NSArray arrayWithObjects:@"img1.png", @"img2.png", @"img3.png", nil]; 
int randomNumber = arc4random() % [myImageArray count];
[imageView setImage:[UIImage imageNamed:[myImageArray objectAtIndex:(randomNumber)]];

The assumptions here are that you have a static list of possible images and those images are locally stored within the project. This is a quick & dirty implementation of what you're asking to achieve. It also assumes you're using ARC.

Dan
  • 5,153
  • 4
  • 31
  • 42