ios - 如何使用 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
}
我做错了什么,你会建议我做什么?
解决方案
为了在 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
}
}
}
推荐阅读
- php - 如何检查带有罗马数字的句子php
- c# - DbContext 错误:在前一个操作完成之前在此上下文上启动了第二个操作
- python - Django Python电子邮件验证多个用户之间没有共享电子邮件
- bash - Azure CLI - 用于设置 API 管理自定义域的 Bash 脚本
- c# - 如何在不中断用户的情况下缓存对象?
- jsoup - 有没有获取 jSoup jar 版本的方法?
- asp.net - aspx.vb 中未提供存储过程的参数
- url - 打开 URL 时 PERSISTED_QUERY_NOT_FOUND
- erlang - 是否可以在不停止我的程序的情况下调用内部调用“halt()”的函数?
- reactjs - React useRef 不适用于 Material UI TextField