首页 > 解决方案 > 如何使用 segues 将数据传递给另一个视图控制器的函数?

问题描述

我想从一个 ViewController 传递数据以在另一个 ViewController 中运行。函数 init 必须从第一个视图控制器获取输入并将其分配给goalDescription变量goalTypes

我执行以下操作:

第一个视图控制器

 @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)

第二个视图控制器

 var goalDescription: String!
 var goalType: GoalType!  

    func initData(description: String, type: GoalType) {
        self.goalDescription = description
        self.goalType = type
    } 

我做错了什么,你会建议我做什么?

标签: iosswift

解决方案


为了在 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  
        }
    }
}

推荐阅读