如何在 xCode 中以编程方式设置图像

how to set image programmatically in xCode

我有个小问题。我尝试了一些东西,byt 是不正确的。我不知道如何为每个问题设置图像。你能帮我吗? (我是初学者)谢谢


我的代码在这里:

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 { [=11=].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)
       }

   }

您需要创建一个 @IBOutlet,方法是按住 control 然后单击并从故事板拖动到您的视图控制器,它会询问您是否要创建一个 outlet 在那里释放它,您将得到像这样的弹出窗口:

为您的 UIImageView 取一个合适的名称,然后单击“连接”,您会发现一个新行已添加到您的视图控制器中,如下所示:

@IBOutlet weak var imageQuestion: UIImageView!

现在你只需要通过调用

来设置图像
imageQuestion.image = UIImage(named: questions[numberOfQuestion].image)