How to pass data from viewcontroller A to another

2020-03-08 06:48发布

I am creating instance of ViewControllerB from ViewControllerA using instantiateViewControllerWithIdentifier(identifier: String) function.

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)
  }

}

I want to access value which i have passed in my ViewControllerB how can i achieve this.

i alredy gone through Passing Data between View Controllers link but the answers in objective c.

标签: ios swift3
3条回答
等我变得足够好
2楼-- · 2020-03-08 07:21

You just can declare a var in your VCB viewController and inject data to this property

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)
  }

}
查看更多
时光不老,我们不散
3楼-- · 2020-03-08 07:23

Just use this code send data from one view controller to anotherview controller

   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)
查看更多
冷血范
4楼-- · 2020-03-08 07:24

You may try

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.
}

}

And the other 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.
}


}
查看更多
登录 后发表回答