在ios中随机更改UILabel文本

时间:2014-01-25 06:45:22

标签: objective-c uiviewcontroller ios7 uilabel

在我的应用程序中,我想随机更改uilabel文本,但无法使用以下代码随机更改。

if (app.l == 0 || app.l%5 == 0) {
    textLabel.text = @"Just pick up a pen  and put it down on the paper.See what you create.";
}
else if(app.l == 1 || app.l%5==1)
{
    textLabel.text = @"Turn on your favourite sport event and let yourself get into it.";
}

请帮忙。 我需要在每次用户输入viewcontroller时随机更改文本。 是否可以使用标签来更改文本。 在此先感谢。

2 个答案:

答案 0 :(得分:2)

textLabel.text = (arc4random_uniform(100)>50)?
         (@"Just pick up a pen  and put it down on the paper.See 
         what you create."):(@"Turn on your favourite sport event 
         and let yourself get into it.");

arc4random_uniform(N)会将NSUInteger从0返回到N

如果您想添加更多文字:

NSArray *list = [[NSArray alloc] initWithObjects: @"1", @"2", @"3", @"4",@"5", nil];
    textLabel.text = [list objectAtIndex:arc4random_uniform(list.count)];

答案 1 :(得分:0)

您想获得一个随机值,使用arc4random()来执行此操作。这将返回0到(2 ** 32)-1之间的随机数。这对我们有什么帮助?我们真正想要的只是两个随机数,0或1,所以我们可以在两个标签之间进行选择。我们使用%执行此操作,arc4random()%2将数字除以并给出余数。如果我们arc4random()%4,如果数字是偶数,我们将得到0,如果数字是奇数,我们将得到1。

如果我们arc4random_uniform(),我们会得到0,1,2或3。

编辑:实际上另一个答案是一个很好的建议。 arc4random_uniform(100)/50会为我们这样做。但不是arc4random_uniform(2),而是int randomNum = arc4random() % 2; if (randomNum==0) { textLabel.text = @"Just pick up a pen and put it down on the paper.See what you create."; } else { textLabel.text = @"Turn on your favourite sport event and let yourself get into it."; } ,你可以真正做{{1}},这将返回0或1的随机数。

无论哪种方式,我们都可以在if块中使用该随机数来随机选择文本。一半时间它将为零,一半时间不会,所以在你的else语句中使用它。

{{1}}