suchen

Heim  >  Fragen und Antworten  >  Hauptteil

ios - swift通过属性传值,返回为空,怎么解决?

新手敲代码,想从一个页面通过点击按钮往另外一个页面传值,通过属性传值的方式传递两个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)")
}
怪我咯怪我咯2771 Tage vor487

Antworte allen(1)Ich werde antworten

  • ringa_lee

    ringa_lee2017-04-18 09:50:23

    你 secondVC 就是一局部变量……

    performSegue 后,会有 prepare(for segue: UIStoryboardSegue, sender: Any?) 这个步骤。在这里,可以获取到 segue 的 identifier, destination。

    拿到 destination 后,修改 destination 内的属性即可。

    简单的例子:

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

    如果你想自己创建 ViewController 并 push ,可以用 navigationController 的 push 或者用 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)
        }

    Antwort
    0
  • StornierenAntwort