在视图控制器之间传递数据无法正常工作
Pass data between view controllers is not working correctly
希望你们今天过得愉快并保持安全!我试图在两个视图控制器之间传递数据,但似乎没有任何变化。这是我的第一个视图控制器:
import UIKit
class AddFoodViewController: UIViewController {
@IBOutlet weak var foodTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "toTableViewController") {
print("hello world")
let destinationViewController = TableViewController()
destinationViewController.food.append(foodTextField.text!)
let homeViewController = storyboard?.instantiateViewController(identifier: "TableViewController") as? TableViewController
view.window?.rootViewController = homeViewController
}
}
}
在第二个视图控制器中,数组食物似乎根本没有改变,当我打印它时它仍然是空的。任何帮助将不胜感激!
您似乎正在创建 destinationViewController
并向其附加 food
,但您并未使用它。您需要在实例化 TableViewController
之后追加 food
,方法如下:
var food = [String]()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "toTableViewController") {
let homeViewController = storyboard?.instantiateViewController(identifier: "TableViewController") as? TableViewController
food.append(foodTextField.text!)
homeViewController.food = food
view.window?.rootViewController = homeViewController
}
}
希望你们今天过得愉快并保持安全!我试图在两个视图控制器之间传递数据,但似乎没有任何变化。这是我的第一个视图控制器:
import UIKit
class AddFoodViewController: UIViewController {
@IBOutlet weak var foodTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "toTableViewController") {
print("hello world")
let destinationViewController = TableViewController()
destinationViewController.food.append(foodTextField.text!)
let homeViewController = storyboard?.instantiateViewController(identifier: "TableViewController") as? TableViewController
view.window?.rootViewController = homeViewController
}
}
}
在第二个视图控制器中,数组食物似乎根本没有改变,当我打印它时它仍然是空的。任何帮助将不胜感激!
您似乎正在创建 destinationViewController
并向其附加 food
,但您并未使用它。您需要在实例化 TableViewController
之后追加 food
,方法如下:
var food = [String]()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "toTableViewController") {
let homeViewController = storyboard?.instantiateViewController(identifier: "TableViewController") as? TableViewController
food.append(foodTextField.text!)
homeViewController.food = food
view.window?.rootViewController = homeViewController
}
}