随机选择一个插座并设置其他插座

时间:2015-05-19 05:58:18

标签: ios swift random uibutton variable-assignment

我有一个选择随机UIButton的函数,并将其角色设置为某个表情符号。我现在想要将剩余的UIButtons设置为随机表情符号。

如何确定哪个UIButtons未从随机生成器中设置为一个值?

另外,我想确保分配的值与随机生成器中插入的值不同。

@IBOutlet weak var topLeftAnswer: UIButton!
@IBOutlet weak var topRightAnswer: UIButton!
@IBOutlet weak var bottomLeftAnswer: UIButton!
@IBOutlet weak var bottomRightAnswer: UIButton!

 func correctAnswerGen() {
    var correct: UInt32 = arc4random_uniform(4)
    switch correct{
    case 0: topLeftAnswer.setTitle("", forState: UIControlState.Normal)
    case 1: topRightAnswer.setTitle("", forState: UIControlState.Normal)
    case 2: bottomLeftAnswer.setTitle("", forState: UIControlState.Normal)
    case 3: bottomRightAnswer.setTitle("", forState: UIControlState.Normal)
    default: break
    }
    //assign other 3 buttons to another emoji value.
}

2 个答案:

答案 0 :(得分:1)

要设置随机表情符号,您可以遍历0x1F601...0x1F64F,并选择一个随机表情符号,如:

var rand: UInt32 = arc4random_uniform(78)

for i in 0x1F601...0x1F64F {
    if rand == i {
          var c = String(UnicodeScalar(i))
          print(c)
          break
    }
}

但是因为还有更多的表情符号,你必须使用这样的东西来循环所有表情符号:

let allEmojis = [
    0x1F601...0x1F64F,
    0x2702...0x27B0,
    0x1F680...0x1F6C0,
    0x1F170...0x1F251
]

var rand: UInt32 = arc4random_uniform(544)
var counter = 0
for range in allEmojis {
    for i in range {
        if rand == counter
        {
            var c = String(UnicodeScalar(i))
            print(c)
        }
        counter++
    }
}

答案 1 :(得分:1)

同样简化:

func randomEmoji() -> String{
    let emojies = [UInt32](0x1F601...0x1F64F)
    + [UInt32](0x2702...0x27B0)
    + [UInt32](0x1F680...0x1F6C0)
    + [UInt32](0x1F170...0x1F251)

    let rand = Int(arc4random_uniform(UInt32(emojies.count - 1)))

    return String(UnicodeScalar(emojies[rand]))
}