Search code examples
swiftxcodeuiimageviewuiimage

how to set image programmatically in xCode


i have a little problem. I something tried, byt is is not correct. I have no idea, how to set image for every question. Can you help me, please? (i am beginner) thank you

enter image description here


my code is here:

class HardQuizViewController: UIViewController {

@IBOutlet weak var labelQuestion: UILabel!

@IBOutlet weak var buttonA: UIButton!
@IBOutlet weak var buttonB: UIButton!
@IBOutlet weak var buttonC: UIButton!

@IBOutlet var buttons: [UIButton]!

@IBOutlet weak var imageQuestion: UIImageView!
@IBOutlet weak var tryAgainButton: UIButton!

var numberOfQuestion = -1
var score = 0

let questions = [
    HardQuestion(text: "What is it?", image: "pencil.jpg", correctAnswer: "pencil"),
    HardQuestion(text: "What is in the picture?", image: "apple.jpg", correctAnswer: "apple"),
    HardQuestion(text: "What animal is it?", image: "cat.jpg", correctAnswer: "cat")]

   let answers = [
       ["pencil","rubber","glue"],
       ["apple","pear","strawberry"],
       ["cat","dog","butterfly"]
       ].map { $0.shuffled()}

   @objc func updateUI(){
       if numberOfQuestion < questions.count - 1{
           numberOfQuestion += 1
       }
       labelQuestion.text = questions[numberOfQuestion].text


       //imageQuestion.image = UIImage(named: questions[numberOfQuestion].imageQuestion)

       buttonA.backgroundColor = UIColor.clear
       buttonB.backgroundColor = UIColor.clear
       buttonC.backgroundColor = UIColor.clear


       for (index, button) in buttons.enumerated() {
           button.setTitle(answers[numberOfQuestion][index], for: .normal)
       }

   }

Solution

  • You need to create an @IBOutlet by holding down control and click and drag from the storyboard to your view controller and it'll ask if you want to create an outlet release it there and you'll get a popup like this:

    Outlet

    Give a suitable name for your UIImageView and click connect and you'll find a new line added to your view controller like this:

    @IBOutlet weak var imageQuestion: UIImageView!
    

    Now you just need to set the image by calling

    imageQuestion.image = UIImage(named: questions[numberOfQuestion].image)