-4

我想这很简单,但我找不到完全适合我的问题的答案。我想制作一个按钮,从我给他的列表中打开一个随机 URL,比如说 - 谷歌、youtube 和 facebook 仅用于示例。这是我现在只连接到谷歌的代码行......:

- (IBAction)site:(id)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://google.com"]];
}

有人可以告诉我要在代码中添加什么,以便它也会随机选择这些其他网站吗?

4

1 回答 1

1

就像大力水手所说,您可以将 URL 存储到 aNSArray中并随机选择其中一个:

#include <stdlib.h>

- (IBAction)site:(id)sender {
    NSArray *urls = @[
        [NSURL URLWithString:@"http://www.google.com"],
        [NSURL URLWithString:@"http://www.facebook.com"],
        [NSURL URLWithString:@"http://www.twitter.com"]
    ];

    int index = arc4random_uniform(urls.count);
    NSURL *randomURL = urls[index];

    if ([[UIApplication sharedApplication] canOpenURL:randomURL])
        [[UIApplication sharedApplication] openURL:randomURL];
}
于 2015-01-18T21:25:34.073 回答