简体   繁体   English

iOS随机图片

[英]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. 例如,此代码始终显示第4张图像。

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. 我有与rand()可预测的相同问题。 switched to arc4random() and life got better. 切换到arc4random(),生活变得更好。

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). 尝试arc4random_uniform(upper_bound)。 It returns a number between 0 and upper_bounds-1 它返回0到upper_bounds-1之间的数字

这样尝试

   int randomImages = random()%4;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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