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

How to pass data from viewcontroller A to another viewcontroller B using swift 3

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

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 中传递的值,我该如何实现。

我已经通过了 Passing Data between View Controllers link 但 objective 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.
}

}

还有另一个class

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)