直接初始化一个viewController

Direct initializing of a viewController

我的期望输出:

我想通过直接初始化秒来传递数据viewController

我的第一个 vc :

class MainViewController : UIViewController {

    @IBAction func nextQuestion(_ sender: UIButton ) {

        //enter code here
         questionIndex += 1
         let currentQuestion = exam1[questionIndex]
         questionLabel.text = currentQuestion.question
        //enter code here
        let svc = SecondViewController()
        svc.label.text = "some data from mainvc"  
}

我的第二个vc :

class SecondViewController : UIViewController {
    @IBOutlet weak var label : UILabel! 
}

// 当我编写模拟器工作的代码时,没有显示任何错误。但是当涉及到向 svc 发送数据时,应用程序崩溃并给出错误“在展开可选时发现 nil”

问题是当你这样做时:

let svc = SecondViewController()

您正在初始化,但没有输入情节提要中的信息(假设您使用的是情节提要)。因此,UILabel 永远不会被初始化。

解决方案

为了解决替换行:

let svc = SecondViewController()

let svc = UIStoryboard(name: "YourStoryboardName", bundle: nil).instantiateViewController(withIdentifier: "YourViewIdentifier") as! SecondViewController