IOS Random Images

2019-09-06 20:16发布

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?

3条回答
等我变得足够好
2楼-- · 2019-09-06 21:09
((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)]];
查看更多
一夜七次
3楼-- · 2019-09-06 21:11

try like this,

   int randomImages = random()%4;
查看更多
叛逆
4楼-- · 2019-09-06 21:16

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

查看更多
登录 后发表回答