Search code examples
objective-cuibuttonarc4random

UIButton with random text/value or tag


I have 10 UIButtons created in historyboard, OK?
I want to add random numbers that do not repeat these numbers, ie, numbers from 0 to 9 that interspersed whenever the View is loaded.

I tried to find on Google and here a way to use my existing buttons ( 10 UIButton ), and just apply them to random values​​. Most ways found ( arc4random() % 10 ), repeat the numbers.

All results found that creating buttons dynamically. Anyone been through this?


Solution

  • Create an array of the numbers. Then perform a set of random swapping of elements in the array. You now have your unique numbers in random order.

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