0

I just started learning swift and i have a question. I have two view controllers, and i'm trying to send a string from view 1 to view 2.

This is what i've got so far:

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier =="1"
{
let DestViewControl = segue.destination as! ViewController2
DestViewController.count = 9
}
}

Count is a variable in view 2. So far this works great. However, if i want to automatically change the text in a label in view 2, as DestViewController.lb_ExLabem.text = "test" , i get a fatal error "unexpectedly found nil while unwrapping an optional value".

Let me know if you have any ideas.

Thanks

Necro1992
  • 139
  • 1
  • 10

3 Answers3

1

lb_ExLabem is in your DestViewController and when you are trying to set it like this

 DestViewController.lb_ExLabem.text = "test"

the value is nil.(As the view is lot loaded)

try to set the value of lb_ExLabem in viewWillAppear() of DestViewController it will work

Rajat
  • 10,977
  • 3
  • 38
  • 55
1

Before the segue, you outlet is nil (since the view is not loaded).

In DestViewController, you should create a variable to store the text:

class ViewController2{
    @IBOutlet weak var your_label: UILabel!
    var label_tex=String()
}

Initiate it in prepareForSegue:

override func prepare(for segue: UIStoryboardSegue, sender: Any?){
    if segue.identifier =="1"{
        let DestViewControl=segue.destination as! ViewController2
        DestViewController.label_tex="9"
    }
}

And finally in ViewController2, change your label text when the view is loaded (and your outlet not nil anymore):

override func viewWillAppear(_ animated: Bool){
    your_label.text=label_tex
}
Marie Dm
  • 2,637
  • 3
  • 24
  • 43
  • 1
    Thanks, thought of this bypass and did it in viewDidLoad, i was just trying to find a way without assigning the label. – Necro1992 Nov 18 '16 at 16:10
0

The error simply means that the value of your DestViewController.lb_ExLabem variable is nil. Make sure that the variable has a value in it so you don't get an error.

RyanM
  • 751
  • 5
  • 20