Reputation: 82
In ViewController:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "Segue") {
var svc = segue.destinationViewController as! ViewController2;
svc.vericik = self.vericik
}
}
@IBAction func gotoView2(sender: AnyObject) {
self.performSegueWithIdentifier("Segue", sender: self)
self.presentViewController(ViewController2(), animated: true, completion: nil)
}
In ViewController2:
var vericik: String!
@IBOutlet weak var VeriYeri: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
VeriYeri.text = vericik
}
When, I click button on ViewController, ViewController2 page comes to screen and I can see segue data which come from ViewController. But after that, an error occurs:
fatal error: unexpectedly found nil while unwrapping an Optional value
Where am I doing wrong?
Upvotes: 1
Views: 433
Reputation: 154513
Your problem is this line:
self.presentViewController(ViewController2(), animated: true, completion: nil)
This line of code is creating a second ViewController2
. The first one was created for you when you did self.performSegueWithIdentifier("Segue", sender: self)
. This second ViewController2
never gets initialized, so its vericik
property is still nil
when viewDidLoad
runs and implicitly unwraps the optional with VeriYeri.text = vericik
(because vericik
is declared as String!
).
To fix the problem, simply delete this line of code:
self.presentViewController(ViewController2(), animated: true, completion: nil)
It is not needed. The segue creates ViewController2
for you, and you initialize it in prepareForSegue
, and then the segue presents ViewController2
. There's absolutely no need for you to call presentViewController
when using segues.
Upvotes: 1
Reputation: 2297
You need to check that your string is not nil. Try this.
ViewController2
override func viewDidLoad() {
super.viewDidLoad()
if vericik != nil {
//String is not nil, set textfield/label whatever
VeriYeri.text = vericik
}
}
ViewController
if (segue.identifier == "Segue") {
var svc = segue.destinationViewController as! ViewController2;
if self.vericik != nil {
//String is not nil. All is good :)
svc.vericik = self.vericik
} else {
//String is nil, do something...maybe set default text
svc.vericik = "some text"
}
}
Upvotes: 0
Reputation: 1194
Somehow, you are setting your vericik
variable to nil
. Can you print that value before you try setting it before the segue? If it's nil
, don't set it as the text, because that's causing the crash.
Upvotes: 0