Rumah > Soal Jawab > teks badan
新手敲代码,想从一个页面通过点击按钮往另外一个页面传值,通过属性传值的方式传递两个string,但是在第二个页面获取传到的值得时候,发现是空的,怎么解决?求教各位.
第一个页面:
func pushView(){
let secondVC = secondViewController()
secondVC.titleGo = "百度一下"
secondVC.address = "https://www.baidu.com"
self.performSegue(withIdentifier: "secondViewController", sender: self)
print("======")
}
第二个页面:
class secondViewController: UIViewController {
@IBOutlet weak var itemBar: UINavigationItem!
var netAddress = String()
var address = String()
var titleGo = String()
var webView = WKWebView()
override func viewDidLoad() {
itemBar.title = titleGo
print("======+\(titleGo)")
netAddress = address
print("++++++=\(address)")
}
ringa_lee2017-04-18 09:50:23
VC kedua anda ialah pembolehubah setempat...
SelepasperformSegue
, akan ada prepare(for segue: UIStoryboardSegue, sender: Any?)
langkah. Di sini, anda boleh mendapatkan pengecam dan destinasi segue.
Selepas mendapat destinasi, cuma ubah suai atribut dalam destinasi.
Contoh mudah:
@IBAction func btn1Pressed(_ sender: Any) {
performSegue(withIdentifier: "segue1", sender: self)
}
@IBAction func btn2Pressed(_ sender: Any) {
performSegue(withIdentifier: "segue2", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue1" {
if let target = segue.destination as? ViewController1 {
target.text = "segue1"
target.num = 1
}
} else if segue.identifier == "segue2" {
if let target = segue.destination as? ViewController2 {
target.text = "segue2"
target.num = 2
}
}
}
Jika anda ingin mencipta ViewController sendiri dan menolaknya, anda boleh menggunakan navigationController push
atau viewController present
:
func test() {
let vc = ViewController1()
vc.text = "111"
vc.num = 3
// 这样显示
// in navigation controller
self.navigationController?.pushViewController(vc, animated: true)
// 或者这样
// present modal viewController
//self.present(vc, animated: true, completion: nil)
}