Brandon Houlihan
Brandon Houlihan

Reputation: 209

IOS Random Image in Image View when the view loads

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.

Upvotes: 0

Views: 759

Answers (2)

Dan
Dan

Reputation: 5173

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.

Upvotes: 0

picciano
picciano

Reputation: 22701

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.

Upvotes: 1

Related Questions