Question

I have an Array with 26 Alphabets and Second Array with 3 UIButtons. I want to take random 3 Alphabets from the Array and Set them randomly As a Titles of 3 UIButtons .here is code.

-(void)placeImages {
     NSMutableArray *alphabetarr=[[NSArray alloc]  
     initWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",
     @"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",nil];
     NSMutableArray *buttons = [NSArray arrayWithObjects:btn1, btn2, btn3, nil];
     for (UIButton *btn in buttons) {
           int randomIndex= arc4random() % [alphabetarr count];
           NSString* titre = [alphabetarr objectAtIndex:randomIndex];
           [btn setTitle:titre forState:UIControlStateNormal]; 
           [alphabetarr removeObjectAtIndex:randomIndex];                        
    }

Through using this code i seen only one alphet in one UIButton..please Suggest any one how Can I pick 3 random alphatbet from an Array and set these 3 random alphabets as Titles of 3 UIButtons of array.

Was it helpful?

Solution

Try this to generate random character. No need to set up an array for that.

char c = (char)('A' + arc4random_uniform(25))

Refer here.

OTHER TIPS

-(void)placeImages {
 NSMutableArray *alphabetarr=[[NSMutableArray alloc]  
 initWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",
 @"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",nil];
 NSMutableArray *buttons = [NSMutableArray arrayWithObjects:btn1, btn2, btn3, nil];
 for (UIButton *btn in buttons) {
       int randomIndex= arc4random() % [alphabetarr count];
       NSString* titre = [alphabetarr objectAtIndex:randomIndex];
       [btn setTitle:titre forState:UIControlStateNormal]; 
       [alphabetarr removeObjectAtIndex:randomIndex];                        
}

the allocation was of NSArray instead of NSMutableArray. this should work. hope it helps. happy coding :)

removeObjectAtIndex: is an NSMutableArray method, not NSArray's. Change your alphabetarr type and the problem should go away.

Use the rand() or the arc4random() function for number generation. Here you can see a comparison between the two.

It looks like the problem is that you're overwriting the contents of the button text each time with a new letter. You'll want to save the previous text from the button and append the new character each time rather than resetting it with each new letter.

//gather random letter
NSString *titre = [alphabetarr objectAtIndex:randomIndex];

//gather current string
NSMutableString *currentString = [[btn titleLabel] text];

//append string
[currentString appendString:titre];

//set button text
[btn setTitle:currentString forState:UIControlStateNormal];

That should append a new letter to the button each time, rather than setting it to the last letter returned from the random array.

Hope that helps :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top