lapacino
lapacino

Reputation: 171

how to randomize my image view?

i want every time when i hit the button next a random image different of the current

this is the code that i use but sometime the image didn't update:

    @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"


}

Upvotes: 0

Views: 63

Answers (2)

Glorfindel
Glorfindel

Reputation: 22631

Well, because of this line

currentIndex = indexPath

the next line always returns true:

if currentIndex == indexPath {

so indexPath is set on the next line

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

and it has a 1 in 4 chance of being equal to the currently selected image.

You need a do-while loop, to make sure a new random number is selected for as long as necessary:

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

You can set currentIndex = indexPath afterwards.

Upvotes: 2

lapacino
lapacino

Reputation: 171

this is how it's work for me :

@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"


}

Upvotes: 0

Related Questions