【问题标题】:The code for switching views randomly is not functioning随机切换视图的代码不起作用
【发布时间】:2014-01-25 22:47:35
【问题描述】:

我有这个代码,目前它不能正常工作。当我单击按钮切换视图时,没有任何反应。我正在使用 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;
}

}

【问题讨论】:

    标签: ios random view switch-statement


    【解决方案1】:

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

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

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

    在 OP 情况下使用:

    int randomviews = arc4random_uniform(2);
    

    【讨论】:

    • 更改代码后,应用程序仍然崩溃。你对它可能是什么还有其他想法吗?
    • 如果应用程序崩溃,请将崩溃日志和回溯添加到问题中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 2020-04-19
    相关资源
    最近更新 更多