如何随机化我的图像视图?

时间:2015-07-31 17:58:40

标签: ios image swift random

我希望每当我按下按钮时,会出现一个与当前不同的随机图像

这是我使用的代码,但有时图像没有更新:

    @IBAction func nextBarButton(sender: UIBarButtonItem) {


    var image1 = UIImage(named: "RedBalloon1.jpg")
    var image2 = UIImage(named: "RedBalloon2.jpg")
    var image3 = UIImage(named: "RedBalloon3.jpg")
    var image4 = UIImage(named: "RedBalloon4.jpg")

    var images = [image1, image2, image3, image4]
    var indexPath = Int(arc4random_uniform(UInt32(images.count)))
    currentIndex = indexPath
    if currentIndex == indexPath {
        indexPath = Int(arc4random_uniform(UInt32(images.count)))
    }

    self.imageView.image = images[indexPath]
    self.balloonLabel.text = "\(count++) Balloon"


}

2 个答案:

答案 0 :(得分:2)

好吧,因为这行

currentIndex = indexPath

下一行始终返回true

if currentIndex == indexPath {

所以indexPath在下一行设置

indexPath = Int(arc4random_uniform(UInt32(images.count)))

并且它有1/4的机会等于当前选择的图像。

您需要do-while loop,以确保在必要时选择新的随机数:

var images = [image1, image2, image3, image4]
var indexPath = 0
do {
    indexPath = Int(arc4random_uniform(UInt32(images.count)))
} while currentIndex == indexPath

之后您可以设置currentIndex = indexPath

答案 1 :(得分:0)

这就是我的工作方式:

@IBAction func nextBarButton(sender:UIBarButtonItem){

    var image1 = UIImage(named: "RedBalloon1.jpg")
    var image2 = UIImage(named: "RedBalloon2.jpg")
    var image3 = UIImage(named: "RedBalloon3.jpg")
    var image4 = UIImage(named: "RedBalloon4.jpg")

    var images = [image1, image2, image3, image4]
    var indexPath = Int(arc4random_uniform(UInt32(images.count)))
    while currentIndex == indexPath {
        indexPath = Int(arc4random_uniform(UInt32(images.count)))
    }
  

currentIndex = indexPath

    self.imageView.image = images[indexPath]
    self.balloonLabel.text = "\(count++) Balloon"


}