2

In my view, i have 12 buttons,and a array contains 6 names , i want to print the array names in UIButton title. Here's my code:

texts = [[NSMutableArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",nil];
UIButton *button;
NSString *name;
NSUInteger count = [texts count];
int i=0;

for(UIView *view in self.view.subviews)
{
    if([view isKindOfClass:[UIButton class]])
    {
        button= (UIButton *)view;
        if(button.tag >= 1||button.tag <= 20)
        {
            int value = rand() % ([texts count] -1) ;
            int myTag= i+1;
            button = [self.view viewWithTag:myTag];
            name=[NSString stringWithFormat:@"%@",[texts objectAtIndex:value]];
            [button setTitle:name forState:UIControlStateNormal];
            NSLog(@"current  name :%@",name);
        }
        i++;
    }

}
[super viewDidLoad];

The problems I am facing are:

  1. While shuffling the values are repeating,i tried with What's the Best Way to Shuffle an NSMutableArray?, its not working.

  2. I want 6 titles in 12 button that means each title will be in 2 buttons. Please help me solve this issue. What changes should I make?

4

2 に答える 2

2

基本的に、シャッフル ロジックをボタン機能に名前を追加することから分離する必要があります。最初に配列をシャッフルしてから、ボタンの名前を設定します。

[super viewDidLoad]; //Always super call should be the first call in viewDidLoad
texts = [[NSMutableArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6", @"1",@"2",@"3",@"4",@"5",@"6", nil];
//adding all 12 button titles to array, use your own logic to create this array with 12 elements if you have only 6 elements

NSUInteger count = [texts count];

for (NSUInteger i = 0; i < count; ++i) {
        // Select a random element between i and end of array to swap with.
        NSInteger nElements = count - i;
        NSInteger n = (arc4random() % nElements) + i;
        [texts exchangeObjectAtIndex:i withObjectAtIndex:n];
}

UIButton *button = nil;
NSString *name = nil;
int i = 0;

for(UIView *view in self.view.subviews)
{
    if([view isKindOfClass:[UIButton class]])
    {
        button= (UIButton *)view;
        if(button.tag >= 1 && button.tag <= 20)
        {
            name = [NSString stringWithFormat:@"%@",[texts objectAtIndex:i]];
            //assuming that the above texts array count and number of buttons are the same, or else this could crash
            [button setTitle:name forState:UIControlStateNormal];
            NSLog(@"current  name :%@",name);
            i++;
        }
    }
}
于 2012-11-05T07:13:52.293 に答える
1

NSMutableArrayのカテゴリを作成します

@implementation NSMutableArray (ArrayUtils)
- (void)shuffle{
static BOOL seeded = NO;
if(!seeded)
{
    seeded = YES;
    srandom(time(NULL));
}
NSUInteger count = [self count];
for (NSUInteger i = 0; i < count; ++i) {
    // Select a random element between i and end of array to swap with.
    int nElements = count - i;
    int n = (random() % nElements) + i;
    [self exchangeObjectAtIndex:i withObjectAtIndex:n];
}
}
@end
于 2012-11-05T07:38:20.977 に答える