简体   繁体   中英

How do I change a UIImage for another UIImage by clicking a button in Swift 3?

I'm trying to make an app for kids so that they can make a relationship between images and words. A UIImage (representing an everyday object) appears on a UIImageView and the kids have to type on the text field the name of the object they're seeing (eg there's a yellow car with a luminous top sign on the view and they have to type 'taxi'). Then, they click on a 'next' button and a new image appears. I've been looking through this site, and this is the code I have right now:

class wordPracticeViewController: UIViewController{
    let currentWord = "taxi"
    var imageName = "taxi.png"
    var answer : String = ""

    var image = UIImage()
    var imageView = UIImageView()

    @IBOutlet weak var inputText: UITextField!
    @IBOutlet weak var ima: UIImageView!

    override func viewDidLoad()
    {
        super.viewDidLoad()

        image = UIImage(named: imageName)!
        imageView = UIImageView(image: image)
        imageView.frame = CGRect(x: 160, y: 80, width: 100, height: 200)
        view.addSubview(imageView)
    }

    @IBAction func answer(_ sender: Any)
    {
        answer = inputText.text!
        print("\(answer)")

        if answer == currentWord
        {
            imageName = "blanket.png"
            imageView.image = UIImage(named: "blanket")
        }
    }
}

Now, my biggest problem is that I want the image to change whether they spell the word correctly or not, because I'm planning to save the results and when they're done playing, the app will show them their scores, the words they spelled correctly and the ones they didn't. Of course, I need that a relationship between the word and the image exists (if not, how are they going to get the right word for the right image?), that's why I put the condition answer == currentWord , but in the long term that's not what I need.

With my current code, the image only changes if they have the right word & spelled correctly. So, how can I change UIImages in a view with a click, whether they've spelled the word correctly or not, keeping the relationship between image and word?

How about creating a class which would include as properties: image file name, correct answer word, and an array of acceptable misspelled words? Then in the answer function, you check if the text input matches any of the acceptable misspellings or the correct answer, or is incorrect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM