在 Swift 中的视图控制器之间传递数据 [英] Passing Data between View Controllers in Swift

查看:30
本文介绍了在 Swift 中的视图控制器之间传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将应用程序从 Objective-C 转换为 Swift,但我找不到如何使用 Swift 在视图之间传递数据.我的 Objective-C 代码是

I am trying to convert an app from Objective-C to Swift but I can't find how to pass data between views using Swift. My Objective-C code is

UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
AnsViewController *ansViewController;
ansViewController = [storyBoard instantiateViewControllerWithIdentifier:@"ansView"];
ansViewController.num = theNum;
[self presentViewController:ansViewController animated:YES completion:nil];

它所做的基本上是获取变量 theNum,并将其传递给不同视图控制器上的变量 num.我知道这可能是一个简单的问题,但我对 Swift 感到很困惑,所以如果有人能解释他们如何将其更改为 Swift,我们将不胜感激!

What that is doing is it basically takes the variable, theNum, and passes it to the variable, num, on a different view controller. I know this may be an easy question but I am getting pretty confused with Swift so if someone could explain how they changed it to Swift that would be greatly appreciated!

谢谢

推荐答案

假设我们站在 firstView 转到 DetailView 并希望将数据从 firstView 传递到 Detailview.要使用 storyboard 做到这一点,在 firstView 我们将有一个方法:

Let's assumed we stand at the firstView go to the DetailView and want passing data from firstView to Detailview. To do that with storyboard, at the firstView we will have a method:

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类我们声明了一个变量:

and then into the class of DetailView we declared a variable:

var toPass: String!

然后你可以使用变量toPass(当然你可以根据需要更改变量的类型,在这个EX中我只是演示字符串类型).

then you can use the variable toPass (of course you can change the type of the variable as you want, in this EX I just demo for string type).

这篇关于在 Swift 中的视图控制器之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆