我想将数据从一个ViewController传递到另一个ViewController中。函数初始化必须从第一个视图控制器获取输入,并将其分配给goalDescription
和goalTypes
变量。
我执行以下操作:
第一个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)
第二个ViewController
var goalDescription: String!
var goalType: GoalType!
func initData(description: String, type: GoalType) {
self.goalDescription = description
self.goalType = type
}
我做错了什么,你会建议我做什么?
答案 0 :(得分:1)
为了在ViewController之间适当地传递数据,您需要重写prepare(for:sender:)
函数。
在您的情况下:
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
}
}
}