具有随机文本/值或标记的UIButton

时间:2013-03-02 18:40:41

标签: objective-c uibutton arc4random

我在历史记录中创建了10个UIButtons,好吗? 我想添加不重复这些数字的随机数,即每当加载View时散布的数字从0到9。

我试图在Google上找到一种方法来使用我现有的按钮(10 UIButton),然后将它们应用于随机值。找到的大多数方法(arc4random() % 10),重复数字。

所有结果都发现动态创建按钮。有没有人经历过这个?

2 个答案:

答案 0 :(得分:2)

创建数字数组。然后在数组中执行一组随机交换元素。您现在可以按随机顺序获得唯一的数字。

- (NSArray *)generateRandomNumbers:(NSUInteger)count {
    NSMutableArray *res = [NSMutableArray arrayWithCapacity:count];
    // Populate with the numbers 1 .. count (never use a tag of 0)
    for (NSUInteger i = 1; i <= count; i++) {
        [res addObject:@(i)];
    }

    // Shuffle the values - the greater the number of shuffles, the more randomized
    for (NSUInteger i = 0; i < count * 20; i++) {
        NSUInteger x = arc4random_uniform(count);
        NSUInteger y = arc4random_uniform(count);
        [res exchangeObjectAtIndex:x withObjectAtIndex:y];
    }

    return res;
}

// Apply the tags to the buttons. This assumes you have 10 separate ivars for the 10 buttons
NSArray *randomNumbers = [self generateRandomNumbers:10];
button1.tag = [randomNumbers[0] integerValue];
button2.tag = [randomNumbers[1] integerValue];
...
button10.tag = [randomNumbers[9] integerValue];

答案 1 :(得分:1)

@meth有正确的想法。如果你想确保数字没有重复,尝试这样的事情:(注意:top会产生最高的数字。确保这个=&gt;数量,否则这将永远循环,永远和永远;)

- (NSArray*) makeNumbers: (NSInteger) amount withTopBound: (int) top
{ 
     NSMutableArray* temp = [[NSMutableArray alloc] initWithCapacity: amount];

     for (int i = 0; i < amount; i++)
     {
        // make random number
        NSNumber* randomNum; 

        // flag to check duplicates
        BOOL duplicate;

        // check if randomNum is already in your array
        do
        {
            duplicate = NO;
            randomNum = [NSNumber numberWithInt: arc4random() % top];

            for (NSNumber* currentNum in temp)
            {
                if ([randomNum isEqualToNumber: currentNum])
                {
                    // now we'll try to make a new number on the next pass
                    duplicate = YES;
                }
            }
        } while (duplicate)

        [temp addObject: randomNum];
    }

    return temp;
}