Se Mo
Se Mo

Reputation: 21

Random image generator

Im trying to display a random image after the push of a button. I have named the 4 images "gameBall1, gameBall2, gameBall3 and gameBall4" and made outlets for them

Here is my attempt:

@IBAction func startButton(sender: UIButton) {
ImageView.image = UIImage(named: "gameBall(arc4random_uniform(3) + 1).png")
}

I get an error saying "Use of unresolved identifier "ImageView""

Upvotes: 0

Views: 1514

Answers (2)

Vasil Garov
Vasil Garov

Reputation: 4921

First of all check if your IBOutlet is set up correctly to your UIImageView.

Then you can try it like this:

EDIT: In order to get random number between 1 and 4 you should use arc4random_uniform(4) + 1 :

@IBAction func startButton(sender: UIButton) {
    ImageView.image = UIImage(named: "gameBall\(arc4random_uniform(4) + 1).png")
}

Upvotes: 1

Duncan C
Duncan C

Reputation: 131416

Lots of problems.

If it says undefined identifier ImageView then it means that you don't have a variable ImageView that is tied to your UIImageView. You need to fix that.

(Open your view controller's scene in the Storyboard. Open the assistant editor and display the view controller's source code. Control-drag from the image view in interface builder into the body of your view controller to define an outlet.)

(You should name variables beginning with lower case letters btw.)

Your code to set the image name is also wrong. You should create a temporary variable with the name of the image in it and display it with a println statement to check it. You are missing a backslash around the (arc4random_uniform(3) + 1) part. It should read

imageView.image = UIImage(named: "gameBall\(arc4random_uniform(3) + 1).png")

Upvotes: 1

Related Questions