我为我的问题找到了更精确和合乎逻辑的答案,
正如 alpha 提到的,我们需要打乱数组并形成一个排序的数组,我们需要根据索引为 jumbledWord 分配一个随机词,例如:
int randomWordIndex = (int)arc4random%[greWordsArray count];
self.jumbledWord = [greWordsArray objectAtIndex:randomWordIndex];
现在我们已经准备好根据字长创建按钮了。这里是:
-(void)buttonsCreation:(int)noOfButtons
{
NSMutableArray *charactersArray = [NSMutableArray array];
self.wordButtons = [[NSMutableArray alloc]initWithCapacity:20];
BOOL record = NO;
int randomNumber;
for (int i=0; [charactersArray count] < jumbledWord.length; i++) //Loop for generate different random values
{
randomNumber = arc4random() % jumbledWord.length;//generating random number
if(i==0)
{
[charactersArray addObject:[NSNumber numberWithInt:randomNumber]];
}
else
{
for (int j=0; j<= [charactersArray count]-1; j++)
{
if (randomNumber ==[[charactersArray objectAtIndex:j] intValue])
record = YES;
}
if (record == YES)
record = NO;
else
[charactersArray addObject:[NSNumber numberWithInt:randomNumber]];
}
}
int arrayValue;
float x = 100.0;
float y = 100.0;
for(int i=0;i<[jumbledWord length];i++)
{
if(i>=0 && i<10)
{
arrayValue = [[charactersArray objectAtIndex:i] intValue];
x = x + 33;
UIButton *characterButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
characterButton.frame = CGRectMake(x,175.0, 35.0, 35.0);
[wordButtons addObject:characterButton];
NSString *characterValue = [NSString stringWithFormat:@"%c",[jumbledWord characterAtIndex:arrayValue]];
[characterButton setTitle:characterValue forState:UIControlStateNormal];
[characterButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[characterButton setTag:arrayValue];
[self.view addSubview:characterButton];
}
else if(i>=10 && i<15)
{
y = y + 33;
UIButton *characterButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
characterButton.frame = CGRectMake(y,200.0, 35.0, 35.0);
[wordButtons addObject:characterButton];
NSString *characterValue = [NSString stringWithFormat:@"%c",[jumbledWord characterAtIndex:i]];
[characterButton setTitle:characterValue forState:UIControlStateNormal];
[characterButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[characterButton setTag:i];
[self.view addSubview:characterButton];
}
}
}
请注意,x 和 y 值可能会因个人要求而异。我已经根据字长简要设置了 x 和 y 的坐标位置,您可以根据需要更改,谢谢 :)
希望它可以帮助一些人,快乐的编码!