[英]Show viewController and pass data without storyboard and segue programming
我想将 firstVC 数据传递给 secondVC。
但我不知道如何通过编程。
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)
}
}
我在堆栈中搜索并找到以下答案。
在没有 storyboard、segue、delegate 和 NSUserDefaults 的情况下还有另一个答案吗? 这个答案使用 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)
在第一个 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)
}
在第二个 ViewController 中,//只需定义字符串
var SomeString = ""
//that's it.
您将在 viewDidLoad 中获取数据
override func viewDidLoad() {
super.viewDidLoad()
print(SomeString);
}
为此,您需要使用自定义 init 方法。
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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.