Reputation: 302
in my app i want to change the uilabel text randomly but am not able to change randomly with the following code.
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.";
}
Please help. I need to change the text randomly when each time user enter in to the viewcontroller. And is it possible to use tag to change the text. Thanks in Advance.
Upvotes: 0
Views: 466
Reputation: 3579
You want to get a random value, to do this use arc4random()
. This returns a random number between 0 and (2**32)-1. How does this help us? What we really want is just two random numbers, either 0 or 1 so we can pick between our two labels. We do this by using %
, which divides the number and gives us the remainder. If we do arc4random()%2
we will get a 0 if the number is even, and 1 if it's odd.
If we did arc4random()%4
we would get either 0,1,2 or 3.
EDIT: Actually the other answer is a good suggestion. arc4random_uniform()
will do this for us. But instead of doing arc4random_uniform(100)/50
you can really just do arc4random_uniform(2)
, which will return a random number of either 0 or 1.
Either way, we can use that random number in an if block to pick the text randomly. Half the time it will be zero, half the time it will not be, so use that in your else statement.
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.";
}
Upvotes: 0
Reputation: 263
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)
returns a NSUInteger
from 0 to N
if you want to add more text:
NSArray *list = [[NSArray alloc] initWithObjects: @"1", @"2", @"3", @"4",@"5", nil];
textLabel.text = [list objectAtIndex:arc4random_uniform(list.count)];
Upvotes: 2