如何在swift按钮点击时更改uiimage的图像?

时间:2014-10-04 08:52:04

标签: ios swift uiimage

我正在尝试通过单击swift中的按钮来更改包含图像的uiimage控件。为此,我写了一个简单的“猜我有多少手指”应用程序。我已经阅读了一些stackoverflow文章,但无法解决问题。下面你可以看到我的代码和我的ui。如何在点击时更改更改图像?

这是我的代码:

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.
    }


}

这是我的用户界面:

enter image description here

3 个答案:

答案 0 :(得分:63)

您无需指定资产目录的名称或图片文件的扩展名。尝试删除它们。例如,

myImageView.image = UIImage(named: "tick")

答案 1 :(得分:4)

It may depend on the version of Xcode you are using. For me the following worked:

ImageView.image = UIImage(named: "Elephants.jpg")

答案 2 :(得分:-11)

在斯威夫特:

myImageView = "nameOfImage";