我在历史板中创建了 10 个 UIButton,好吗?
我想添加不重复这些数字的随机数字,即加载 View 时散布的从 0 到 9 的数字。
我试图在 Google 上找到一种使用现有按钮( 10 UIButton )的方法,并将它们应用于随机值。找到的大多数方法( arc4random() % 10
),重复数字。
所有结果都发现动态创建按钮。有人经历过这个吗?
最佳答案
创建一个数字数组。然后对数组中的元素进行一组随机交换。您现在拥有按随机顺序排列的唯一编号。
- (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];
关于objective-c - 带有随机文本/值或标签的 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15178005/