shuffle NSMutableArray不重复并显示在UIButton中

时间:2012-11-05 06:55:57

标签: iphone ios uibutton nsmutablearray

在我看来,我有12个按钮,一个数组包含6个名字,我想在UIButton标题中打印数组名称。这是我的代码:

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];

我面临的问题是:

  1. 虽然重复播放这些值,但我尝试使用What's the Best Way to Shuffle an NSMutableArray?,它无效。

  2. 我想要12个按钮中的6个标题,这意味着每个标题将在2个按钮中。请帮我解决这个问题。我应该做些什么改变?

2 个答案:

答案 0 :(得分: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++;
        }
    }
}

答案 1 :(得分: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
相关问题