objective-c - 带有随机文本/值或标签的 UIButton

标签 objective-c uibutton arc4random

我在历史板中创建了 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/

相关文章:

ios - arc4random() 在 iOS 中给出负数

ios - 只舍入 UIButton 的左侧而不删除 uieffect

ios - 解析后端上传文件的新错误 - 错误 : File name must be a string - PFFile

swift - UIButton 与 @IBinspectable 用于在 Swift/Xcode 中进行本地化

ios - 在 View 中淡入和淡出 UIButton

swift - 使用 addChild 进行不需要的重复

ios - 多次调用 arc4random 并获得相同的数组集

ios - 错误 : "nested pop animation can result in corrupted navigation bar"

ios - 如何在 Xamarin 中创建可点击的 URL?

ios - UIView 没有隐藏,但它里面的按钮是?