0

I have two views. The first one has a UITextView and a button. The second has a UILabel. When I click on the button I would like the text label of the second views to be filled with what was in the textfield of the first view.

I did the following:

@IBAction func tapButton() {
    let vc = storyboard?.instantiateViewController(identifier: "second") as! SViewController
    vc.l.text = t.text
    vc.modalPresentationStyle = .fullScreen
    present(vc, animated: true)
}

l is the UILabel and t is the UITextField. When I run this code it's telling me I am trying to unwrapped l whereas l is nil.

But why l is nil? I mean if I instantiate my second view then it should create the UILabel l and thus l is not nil?

fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88

1 Answers1

0

This happens because your second view controller's view hierarchy hasn't loaded yet, that's why you're getting nil. Simple solution is to keep a string variable in the second view controller and set it in the button tap action. And then in viewDidLoad of the second view controller set the label text.

Asif Mujtaba
  • 447
  • 6
  • 17