ViewDidLoad的随机图像生成器

时间:2013-06-22 14:05:50

标签: ios objective-c

我已经创建了代码,因此:当视图加载时,会显示一个随机图像。 我写了一些代码,但它始终以相同的图像(和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 ... 是否有人使用替代代码块来实现此功能?

2 个答案:

答案 0 :(得分:2)

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

此代码行中没有随机值。

试试这个:

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

有关objective-c

中随机数的信息,请参阅“Generating Random Numbers in Objective-C

答案 1 :(得分:0)

而不是

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

使用

 arc4random(5)

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

arc4random()

的文档
相关问题