简体   繁体   中英

IOS Random Images

I'm trying to have a random image display when the view loads.

I can get an image to display but its not random, it comes up as the position of the %.

For example, this code displays the 4th image all the time.

Here is my code.

{
    [super viewDidLoad];

    int randomImages = rand() % 4;
    switch (randomImages) {
        case 0:
            _imageView.image = [UIImage imageNamed:@"1.png"];
            break;
        case 1:
            _imageView.image = [UIImage imageNamed:@"2.png"];
            break;
        case 2:
            _imageView.image = [UIImage imageNamed:@"3.png"];
            break;
        case 3:
            _imageView.image = [UIImage imageNamed:@"4.png"];
            break;
    }

}

Anyone know what I'm doing wrong?

((arc4random() % 4) + 1)

i had the same issue with rand() being predictable. switched to arc4random() and life got better.

EDIT:

if you want something nice and streamlined you could replace that entire switch block with just the following:

[super viewDidLoad];

_imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.png", ((arc4random() % 4) + 1)]];

Try arc4random_uniform(upper_bound). It returns a number between 0 and upper_bounds-1

这样尝试

   int randomImages = random()%4;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM