I'm trying to make the segue from viewcontroller to 2ndviewcontroller only when my condition is met. I've connected the segue from the button in viewcontroller to the 2ndviewcontroller. So far I have:
@IBAction func switchView(_ sender: AnyObject) {
// if a and b's textfields aren't empty
if(!(a.text?.isEmpty)! && !(b.text?.isEmpty)!) {
a1 = a.text!;
b1 = b.text!;
}else{
// do something
}
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if(identifier == "2ndviewcontroller") {
if(!(a.text?.isEmpty)! && !(b.text?.isEmpty)!) {
return true
}
}
return false
}
With this, I've been able to make the segue ONLY when a and b's textfields are not empty. That's exactly what I want but I also want to pass data from viewcontroller to 2ndviewcontroller as well.
func prepForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "2ndviewcontroller" {
let 2ndviewcontroller = segue.destination as! 2ndviewcontroller
2ndviewcontroller.c = a
}
}
}
I used the code above to pass data from viewcontroller to 2ndviewcontroller. Problem is I don't know how to combine them to both pass data, AND only make the segue when condition is met. When I have both functions, the bool function executes correctly, but prepForSegue does not pass data. When I comment out the bool function, prepForSegue passes the data, but I'm cannot apply a condition for making the segue.
Edit: fixed by using prepareForSegue method provided in the comments below.
As discussed in the comments, the method name should be prepareForSegue
, not prepForSegue
.