尝试将UILabel.text和UIButton.setTitle()初始化为来自另一个类的数据时发现nil

时间:2019-05-17 14:15:40

标签: ios swift

我是Swift应用程序开发的新手,如果我错过了一些简单的事情,请原谅我。我在一个QuizControl类中创建了一个用于依赖项注入的初始化程序。在此初始值设定项中,一个Questions对象(一个Question对象的数组)有一个参数,并且问题是从另一个类传递的,否则它们将被初始化为默认值。
我还试图为这些传递的问题中的各个数据设置按钮的标题和标签。标签应显示问题,按钮应显示答案。 我相信我的麻烦来自解包,因为每次我尝试初始化标签或按钮的文本时,都会收到此错误:

  

致命错误:在隐式展开可选值时意外发现nil

在来这里之前,我尝试了一些解决方案。我尝试将标签的文本和按钮的文本设置为在初始化时创建的占位符字符串,如下所示:
QLabel.text = "Question Placeholder" for i in 0..<Buttons.count { Buttons[i].setTitle("Answer \(i)", for: UIControl.State.normal) }

但是,我仍然得到意外发现的零。 然后,我尝试声明QLabel和Button是可选的,并带有“?”像这样:

@IBOutlet var Buttons: [UIButton]?
@IBOutlet weak var QLabel: UILabel?

而不是我以前尝试过的方式:

@IBOutlet var Buttons: [UIButton]!
@IBOutlet var QLabel: UILabel!

但是,我只得到了情节提要上显示的内容,而不是我之前创建的占位符字符串。我什至确保该类的viewDidLoad()中具有相同的初始化值。我要去哪里错了?好像我已经尝试了一切。
这是初始化器:

init(){
    Questions = []
    correct = 0
    incorrect = 0
    super.init(nibName: nil, bundle: nil)
}
init(Questions: [Question])
{
    super.init(nibName: nil, bundle: nil)
    self.Questions = Questions
    self.correct = 0
    self.incorrect = 0
    QLabel.text = "Question Placeholder"
    for i in 0..<Buttons.count {
        Buttons[i].setTitle("Answer \(i)", for: UIControl.State.normal)
    }
    self.pickQuestion()
}
required init?(coder: NSCoder){
    super.init(coder: coder)
}

和正在调用初始化程序的类的viewDidLoad():

override func viewDidLoad() {
    let torsoQuestions =
        [Question(Question: "My chest hurts and I'm having difficulty breathing", Answers: ["Check for Asthma","Check family history of heart problems","Call an ambulance","Sample diagnosis 3"], Answer: 2),
        Question(Question: "Question 2", Answers: ["Answer 4","Answer 5","Answer 6","Answer 7"], Answer: 0),
        Question(Question: "Question 3", Answers: ["Answer 8","Answer 9","Answer 10","Answer 11"], Answer: 1),
        Question(Question: "Question 4", Answers: ["Answer 12","Answer 13","Answer 14","Answer 15"], Answer: 2),
        Question(Question: "Question 5", Answers: ["Answer 16","Answer 17","Answer 18","Answer 19"], Answer: 3)]
    let quizController1 = TestQuizViewController(Questions: torsoQuestions)
}

让我知道我是否缺少任何重要信息,谢谢。

0 个答案:

没有答案