0

我已经创建了代码,所以:当视图加载时,显示一个随机图像。我写了一些代码,但它总是以相同的图像(和 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;
    }
}

这真是令人沮丧.. 它适用于 IBAction,但不适用于 viewdidload... 有没有人可以替代代码块来让它工作?

4

2 回答 2

2
index = [NSNumber numberWithInt:(([index intValue] + 1) % 6)];

这行代码中没有随机值。

试试这个:

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

有关 Objective-C中随机数的信息,请参阅“在 Objective-C 中生成随机数”

于 2013-06-22T14:07:49.397 回答
0

代替

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

采用

 arc4random(5)

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

arc4random()的文档

于 2013-06-22T14:07:35.687 回答