Reputation: 1
I want to pass data from one ViewController to function in another ViewController. Function init must take input from first view controller and assign it to goalDescription
and goalTypes
variables.
I do the following:
First ViewController
@IBAction func nextBtnPressed(_ sender: Any) {
if goalTextView.text != "" {
guard let finishGoalVC = storyboard?.instantiateViewController(withIdentifier: "FinishGoalVC") as? FinishGoalVC else { return }
finishGoalVC.initData(description: goalTextView.text!, type: goalType)
performSegue(withIdentifier: "finishGoalVC", sender: self)
Second ViewController
var goalDescription: String!
var goalType: GoalType!
func initData(description: String, type: GoalType) {
self.goalDescription = description
self.goalType = type
}
What am I doing wrong and what would you recommend me to do?
Upvotes: 0
Views: 54
Reputation: 561
In order to pass data between ViewControllers appropriately, you need to override prepare(for:sender:)
function.
In your case:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "finishGoalVC" { //in case you have multiple segues
if let viewController = segue.destination as? FinishGoalVC {
viewController.goalDescription = goalTextView.text! // be careful about force unwrapping.
viewController.goalType = type
}
}
}
Upvotes: 1