Objective c 带有随机文本/值或标记的UIButton

Objective c 带有随机文本/值或标记的UIButton,objective-c,uibutton,arc4random,Objective C,Uibutton,Arc4random,我在historyboard中创建了10个UIButton,好吗? 我想添加不重复这些数字的随机数,即,在加载视图时散布的0到9之间的数字 我试图在Google上找到一种使用我现有按钮(10 UIButton)的方法,并将它们应用于随机值​​. 找到的大多数方法(arc4random()%10)重复这些数字 所有结果都发现动态创建按钮是可行的。有人经历过这个吗?@meth有正确的想法。如果您想确保数字不会重复,请尝试以下操作:(注意:top将是生成的最高数字。请确保此=>amount,

我在historyboard中创建了10个UIButton,好吗?
我想添加不重复这些数字的随机数,即,在加载视图时散布的0到9之间的数字

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


所有结果都发现动态创建按钮是可行的。有人经历过这个吗?

@meth有正确的想法。如果您想确保数字不会重复,请尝试以下操作:(注意:top将是生成的最高数字。请确保此=>amount,否则将永远循环;)

-(NSArray*)生成编号:(NSInteger)带上限的金额:(int)top
{ 
NSMUTABLEARRY*temp=[[NSMUTABLEARRY alloc]initWithCapacity:amount];
对于(int i=0;i
创建一个数字数组。然后对数组中的元素执行一组随机交换。您现在有了随机排列的唯一数字

- (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];
-(NSArray*)GeneratorDomainNumbers:(nsInteger)计数{
NSMutableArray*res=[NSMutableArray阵列容量:count];
//填充数字1..count(切勿使用标记0)

对于(i=1;我呃?你的问题目前没有意义,我恐怕-我想翻译过程中可能会丢失一些东西?搜索是你的朋友:让我试试这个可能的重复项。@rmaddy我做了我不想把所有按钮都放在一个数组中的事情。然后我选择了每个位置并输入随机数。它按照我预期的方式工作ed.但这不是我想要的。如果不进入数组,就无法插入随机数。只需通过标记?不需要将按钮放入数组中。我使用@maddy指示的随机生成,但这不是正确的方法,但是,部分是的……但是谢谢!伟大的解决方案!我也想获得标记是的。但我比在数组中插入按钮要好。再次感谢
- (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];