Ios ViewDidLoad随机图像发生器

Ios ViewDidLoad随机图像发生器,ios,objective-c,Ios,Objective C,我已经创建了代码,所以:当视图加载时,显示一个随机图像。 我已经写了一些代码,但它总是以相同的图像(和viewbgcolor)开始 我的代码: -(void)viewDidLoad { index = [NSNumber numberWithInt:(([index intValue] + 1) % 6)]; switch ([index intValue]) { case 0: moodImage.image = [UIImage ima

我已经创建了代码,所以:当视图加载时,显示一个随机图像。 我已经写了一些代码,但它总是以相同的图像(和viewbgcolor)开始

我的代码:

-(void)viewDidLoad
{
    index = [NSNumber numberWithInt:(([index intValue] + 1) % 6)];
    switch ([index intValue]) {
        case 0:
            moodImage.image = [UIImage imageNamed:@"angry.png"];
            self.view.backgroundColor = [UIColor redColor];
            break;

        case 1:
            moodImage.image = [UIImage imageNamed:@"Disappointed.png"];
            self.view.backgroundColor = [UIColor brownColor];
            break;

        case 2:
            moodImage.image = [UIImage imageNamed:@"glad.png"];
            self.view.backgroundColor = [UIColor orangeColor];
            break;
        case 3:
            moodImage.image = [UIImage imageNamed:@"happy.png"];
            self.view.backgroundColor = [UIColor yellowColor];
            break;

        case 4:
            moodImage.image = [UIImage imageNamed:@"sad.png"];
            self.view.backgroundColor = [UIColor grayColor];
            break;

        case 5:
            moodImage.image = [UIImage imageNamed:@"surprised.png"];
            self.view.backgroundColor = [UIColor greenColor];
            break;
    }
}
这真令人沮丧。。 它适用于iAction,但不适用于viewdidload。。。 是否有人可以使用其他代码块来执行此操作?

而不是

[NSNumber numberWithInt:(([index intValue] + 1) % 6)]
使用

您需要为每个viewDidCall形成随机值,从您的代码中它不会发生

文件

这行代码中没有随机值

试试这个:

index = [NSNumber numberWithInt:arc4random_uniform(5)];

有关objective-c中随机数的信息,请参见“”。

我们的更好方法是,完全跳过NSNumber,并将索引设为int.+1。
index = [NSNumber numberWithInt:(([index intValue] + 1) % 6)];
index = [NSNumber numberWithInt:arc4random_uniform(5)];