所以基本上我有一个按钮,每次单击按钮时,我需要我的UIImage随机更改为数组中的三个图像之一。现在,当我单击按钮时会发生什么,它只是选择一个随机图像,然后当我再次单击它时,图像保持不变。
这是我在按钮内写的内容:
@IBAction func scissorButton(_ sender: UIButton) {
playerChoice.image = scissor.png
computerChoice.image = computerArray[randomChoice]
}
大概你生成了一个随机数一次,并将结果存储在randomChoice
中。但是每次点击按钮时,您都需要生成一个新的随机数。
最简单的选择是执行以下操作:
@IBAction func scissorButton(_ sender: UIButton) {
computerChoice.image = computerArray.randomElement()
}
您可以尝试此操作以保证每次单击按钮时都会获得一个新的非相似随机图像
var old = 0
@IBAction func scissorButton(_ sender: UIButton) {
var randomChoice = 0
while randomChoice == old {
randomChoice = Int.random(in: 0..<computerArray.count)
}
old = randomChoice
computerChoice.image = computerArray[randomChoice]
}
试试这个,它对我来说很好:
//Have an array of the name for your image like
let img = ["img1","img2","img3","img4"]
@IBAction func randomImageClick(_ sender: Any){
self.imageView.image = UIImage(named: img[Int.random(in: img.count)]) // Look out for range of index. its size must be equal your array count, otherwise it'll get index out of range
}