随机切换视图的代码不起作用

时间:2014-01-08 01:33:32

标签: ios random views switch-statement

我有这段代码,目前它无法正常运行。当我点击按钮切换视图时,没有任何反应。我在Xcode 5编程。如果你能提供帮助,我们将不胜感激。代码如下所示。

谢谢, 赞恩

- (IBAction)RandomButton:(id)sender {

int randomviews = rand() % 2;
switch (randomviews) {
    case 0:

    {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:
                                    @"Main.storyboard" bundle:[NSBundle mainBundle]];
        Home *Next = [storyboard instantiateViewControllerWithIdentifier:@"SummerWinter"];
        [self presentViewController:Next animated:YES completion:nil];
    }

        break;
    case 1:

    {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:
                                    @"Main.storyboard" bundle:[NSBundle mainBundle]];
        Home *Next = [storyboard instantiateViewControllerWithIdentifier:@"HiBye"];
        [self presentViewController:Next animated:YES completion:nil];
    }

        break;

    default:
        break;
}

}

1 个答案:

答案 0 :(得分:1)

请勿使用rand(),它不是随机的,请使用arc4random()arc4random_uniform()

rand()需要种子并且这是有问题的,如果没有明确的种子,它会以1的种子开始。使用相同的种子,序列是可重复的。

arc4random()不需要种子,它由系统定期播种,是一个加密安全的伪随机数生成器(PRNG)。

在OP案例中使用:

int randomviews = arc4random_uniform(2);