Luis Villavicencio
Luis Villavicencio

Reputation: 107

iOS: Loading random UIImageView when running iOS simulator

I have two images, "image1" and "image2" . What I want to do is that whenever I open the iOS simulator it will load one of these images at random. Is there a way to do that?

Upvotes: 0

Views: 98

Answers (2)

Josh Engelsma
Josh Engelsma

Reputation: 2646

#include <stdlib.h>

@interface YourViewController()
//Add an Image View to the storyboard on your view controller, then add outlet to your code for that image view
@property (weak, nonatomic) IBOutlet UIImageView *anImageView;
@end

@implementation YourViewController

- (void)viewDidLoad
{

    //random number 0 or 1
    int r = arc4random() % 2;
    UIImage *image1 = [UIImage imageNamed:@"image1"];
    UIImage *image2 = [UIImage imageNamed:@"image2"];

    if (r == 0){
        //if random number is 0, set image view to image1 when view loads
        [self.anImageView setImage:image1];
    }
    else{
        //if random number is 1, set image view to image2 when view loads
        [self.anImageView setImage:image2];
    }
 }
@end

Upvotes: 1

Ty Lertwichaiworawit
Ty Lertwichaiworawit

Reputation: 2950

In you ViewDidLoad or wherever you want you want your imageView to be:

//create image array
NSArray *imagesArray = [NSArray arrayWithObjects:[UIImage imageNamed:@"image1.png"], [UIImage imageNamed:@"image2.png"], nil];
//random number
int r = arc4random() % [imagesArray count];

//create imageview
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
[imageView setImage:[imagesArray objectAtIndex:r]];
[self.view addSubview:imageView];

Upvotes: 1

Related Questions