本文介绍了IOS随机图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在视图加载时显示随机图像。
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 %.
例如,此代码始终显示第4张图像。
For example, this code displays the 4th image all the time.
这是我的代码。
{
[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)
我有同样的问题,rand()是可预测的。切换到arc4random(),生活变得更好。
i had the same issue with rand() being predictable. switched to arc4random() and life got better.
编辑:
如果你想要一些不错的东西并简化你可以用以下内容替换整个开关块:
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)]];
这篇关于IOS随机图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!