如何使用swift 3将数据从viewcontroller A传递到另一个viewcontroller B.

我正在使用instantiateViewControllerWithIdentifier(identifier: String)函数从ViewControllerA创建ViewControllerB的instantiateViewControllerWithIdentifier(identifier: String)

 let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewControllerWithIdentifier("vcB") as VCB; rootController!.presentViewController(vc, animated: true, completion: nil) class VCB: UIViewController { required init?(coder aDecoder: NSCoder){ super.init(coder: aDecoder) } } 

我想访问我在ViewControllerB中传递的值,我该如何实现这一点。

我alredy经历了View Controllers链接之间的传递数据,但目标c中的答案。

您可以在VCB viewController中声明一个var并将数据注入此属性

 let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewControllerWithIdentifier("vcB") as VCB; vc.yourData = SOME_DATA rootController!.presentViewController(vc, animated: true, completion: nil) class VCB: UIViewController { var yourData: AnyObject? required init?(coder aDecoder: NSCoder){ super.init(coder: aDecoder) } } 

你可以试试

 import UIKit class ViewControllerA: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func passDataAction(sender: AnyObject) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewControllerWithIdentifier("UIViewControllerB") as! ViewControllerB; vc.dataFromOtherView = "The data is passed" self.presentViewController(vc, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } 

而另一类

 import UIKit class ViewControllerB: UIViewController { var dataFromOtherView: String = "" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. print(dataFromOtherView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } 

只需使用此代码将数据从一个视图控制器发送到另一个视图控制器

  let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc=storyboard.instantiateViewControllerWithIdentifier("secondView") as! ViewControllerB; vc.dataFromOtherView = "The data is passed" self.presentViewController(vc, animated: true, completion: nil)