Displaying images with action in swift?

134 Views Asked by At

I'm a kind new to Xcode/swift, I am trying to build a game where 5 pics need to selected randomly, my code looks something like that :

var options = ["1.png","2.png","3.png","4.png","4.png"]

@IBAction func option1(sender: AnyObject) {

    var randomNumber = Int(arc4random_uniform(5))
    **iphoneChoise.image(options[randomNumber])**   /*This line is not correct*/     

}

Please help!

3

There are 3 best solutions below

2
On BEST ANSWER

Make an @IBOutlet for your image view.

Then, assuming your images are saved in Images.xcassets:

@IBAction func option1(sender:AnyObject){
    var randomNumber = Int(arc4random_uniform(5))
    yourImageViewIBOutlet.image = UIImage(named: options[randomNumber])
}
0
On

You can simplify the code for your random image by using the following code:

var randomImageGeneratorNumber = acr4random_uniform(5) + 1
YourImageView.image = UIImage(named: "\(randomImageGeneratorNumber).png")

This is called "String Interpolation"

Hope this will help you by making your code a bit shorter.

0
On

You should try something like :

yourImageView.image = UIImage(named: "imageName")

In you case, it should like like this :

var options = ["1.png","2.png","3.png","4.png","4.png"]

@IBAction func option1(sender: AnyObject) {
    var randomNumber = Int(arc4random_uniform(5))
    iphoneChoise.image = UIImage(named: options[randomNumber])
}

Make sure the images are within the project (inside the Images.xcassets for example).

If it didn't helped, please provide more information : "what" is _iphoneChoise_ and what error are you facing.