当按下按钮时,从字典/数组中选择随机字符串以在UILabel中显示

时间:2014-10-19 20:50:33

标签: ios objective-c nsarray nsdictionary

我一直在玩一个应用程序,按下按钮时会显示一个随机笑话。

我已经宣布了两个出口(一个用于按钮,另一个用于标签,将显示该笑话)。我已经成功地获得了代码,以便在" jokeButton"被压了。虽然,如何输入大量的笑话,然后在按下笑话按钮时显示一个随机的。

我曾尝试过使用NSArray和NSDictionary,并进行了一些谷歌搜索,但没有成功。

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

self->jokeLabel.text = (@"Welcome to The Joke Panel!");
}

- (IBAction)jokeWasPressed:(id)sender {
NSLog(@"Joke Button Was Pressed");
self->jokeLabel.text = (@"Why did the chicken cross the road? -- To get to the other side!");
}

非常感谢您的帮助! PS对不起,我刚刚开始学习!

2 个答案:

答案 0 :(得分:0)

您正在创建一个字符串数组。下一步是生成一个随机数,并将其作为索引值从数组中获取字符串。

查找arc4random以获取有关创建随机数的信息。

答案 1 :(得分:0)

//Declare "NSMutableArray *arrJokes;" globally

//Initialize array to hold strings which will essentially be the Jokes
arrJokes = [[NSMutableArray alloc] init];

//Add jokes
[arrJokes addObject:@"Joke 1"];
[arrJokes addObject:@"Joke 2"];
[arrJokes addObject:@"Joke ..."];
[arrJokes addObject:@"Joke N"];

//generate a random index between 0 and arrJokes.count
int randomIndex = arc4random()%arrJokes.count;

//pick the string that is at this randomIndex in arrJokes and set it on the label
[jokeLabel setText:arrJokes[randomIndex]];