我正在尝试将应用程序从 Objective-C 转换为 Swift,但我找不到如何使用 Swift 在 View 之间传递数据。我的 Objective-C 代码是
UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
AnsViewController *ansViewController;
ansViewController = [storyBoard instantiateViewControllerWithIdentifier:@"ansView"];
ansViewController.num = theNum;
[self presentViewController:ansViewController animated:YES completion:nil];
它所做的基本上是获取变量 theNum,并将其传递给不同 View Controller 上的变量 num。我知道这可能是一个简单的问题,但我对 Swift 感到非常困惑,所以如果有人能解释他们如何将其更改为 Swift,我将不胜感激!
谢谢
最佳答案
假设我们站在 firstView 处,转到 DetailView 并希望将数据从 firstView 传递到 Detailview。要使用 Storyboard 来做到这一点,在第一个 View 中我们将有一个方法:
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "segueTest") {
//Checking identifier is crucial as there might be multiple
// segues attached to same view
var detailVC = segue!.destinationViewController as DetailViewController;
detailVC.toPass = textField.text
}
}
然后在DetailView类中我们声明了一个变量:
var toPass: String!
然后你可以使用变量toPass
(当然你可以根据需要更改变量的类型,在这个EX中我只是演示了字符串类型)。
关于ios - 在 Swift 中的 View Controller 之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55450825/