Ad

Direct Initializing Of A ViewController

My Desire Output:

i want to pass data with direct initializing of a second viewController

in my first 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"  
}

in my secondvc :

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

// any error is not showed up when I write code an the simulator works. but when it comes to sending data to svc app crashes and gives error " found nil while unwrapping optional"

Ad

Answer

The problem is that when you do:

let svc = SecondViewController()

You are initializing without the information you put in the Storyboard (assuming you are using storyboards). Hence, so the UILabel is never initialized.

Solution

In order to solve that replace the line:

let svc = SecondViewController()

for

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

Ad
source: stackoverflow.com
Ad