I want to pass firstVC data to secondVC.
But I don't know how to pass programming.
Class FirstVC: ViewController {
var firstText: String = "hello"
func goToSecondVC {
var vc: SecondVC = SecondVC()
vc.secondText = firstText
self.show(vc, sender:nil)
}
}
class SecondVC: ViewController {
var secondText: String = ""
override func viewDidLoad() {
print(secondText)
}
}
I search in stack and find following answer.
Have another answer without storyboard,segue,delegate and NSUserDefaults? And this answer use the storyboard.
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "newViewController") as! NewViewController
newViewController.stringVariable = stringVariable
self.present(newViewController, animated: true, completion: nil)
In First ViewController,
@IBAction func Some_Button(_ sender: Any) {
let secndVC = self.storyboard?.instantiateViewController(withIdentifier:
"SecondViewControllerID") as! SecondViewController
let someString = "this is my string" //Whatever You Want to pass.
secndVC.SomeString=someString
self.navigationController?.pushViewController(secndVC, animated: true)
}
In second ViewController, //Just Define String
var SomeString = ""
//that's it.
You Will Get Your Data in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
print(SomeString);
}
To do this you need to use custom init method.
class FirstVC: UIViewController {
var firstText: String = "hello"
func goToSecondVC() {
let vc = SecondVC(text: firstText)
self.navigationController?.pushViewController(vc, animated: true)
}
}
class SecondVC: UIViewController {
var secondText: String = ""
init(text: String) {
secondText = text
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
print(secondText)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.