Reputation: 1390
In my application I'm having 4 buttons. On each click I want to show the UIButton
title shuffled value from array.
I tried this one What's the Best Way to Shuffle an NSMutableArray?
But its not working.
Upvotes: 0
Views: 145
Reputation: 3774
Someplace you make an array :
In your header (.h) file
NSArray *words;
and a little below that
- (IBAction)aButtonWasClicked:(id)sender;
In you code file (.m), like viewDidLoad
words = [[NSArray arrayWithObjects:@"One", @"Two", @"Three", @"Four", nil] retain];
(in ios 6 you might do it like this
words = @[@"One", @"Two", @"Three", @"Four"];
Then you do this :
- (IBAction)aButtonWasClicked:(id)sender {
int value = arv4random() % ([words count] -1);
UIButton *mybutton = (UIButton *)sender;
[mybbutton setTitle:[words objectAtIndex:value] forState:UIControlStateNormal];
}
Just remember to hook all 4 buttons to the same Action.
Thats all there is to it. You can easily add a function to make sure no button has the same title and so on.
Upvotes: 0
Reputation: 1227
You will get your index of array shuffled and then use that index to pick value.
int rndIndex = arc4random()%[yourArray count];
[yourArray objectAtIndex:rndIndex];
Upvotes: 1