Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change uiimage's image on button click in swift?

Tags:

ios

swift

uiimage

I'm trying change an uiimage control's containing image by clicking a button in swift. For this, i wrote a simple a "guess how many fingers i'm holding up" app. I've read some stackoverflow articles but couldn't solve the problem. Below you can see my code and my ui. How can i change change image on click?

Here's my code:

import UIKit

class ViewController: UIViewController {

    @IBOutlet var myImageView: UIImageView!
    @IBOutlet var inputField: UITextField!
    @IBAction func clickedGuessButtonAction(sender: AnyObject) {
        println("Guess button clicked")
        var randomX = Int(arc4random()%6)
        println("randomX = \(randomX)")
        var guess = inputField.text.toInt();

        let image0 = UIImage(named: "images/qm.jpg")
        let image1 = UIImage(named: "images/tick.jpg")
        let image2 = UIImage(named: "images/cross.jpg")

        if((inputField.text) != nil){
            if(guess == randomX){
                println("correct")
                myImageView.image=UIImage(named: "tick.jpg") // THIS IS NOT WORKING
                myImageView.image=image1                     // THIS IS NOT WORKING TOO
                inputField.resignFirstResponder();// hides keyboard
            }
            else
            {
                println("wrong")
                myImageView.image=UIImage(named: "cross.jpg")
                inputField.resignFirstResponder();//hides keyboard
            }
        }
        else{
            println("invalid input. requires integer only")
            inputField.resignFirstResponder();// hides keyboard
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

And here's my UI:

enter image description here

like image 494
t1w Avatar asked Sep 11 '25 17:09

t1w


1 Answers

You don't need to specify either the asset catalog's name or the image file's extension. Try removing those. For example,

myImageView.image = UIImage(named: "tick")
like image 140
Isuru Avatar answered Sep 14 '25 08:09

Isuru