无法在UIStoryBoard segue中传递值

时间:2018-04-11 13:32:26

标签: ios swift segue uistoryboard uistoryboardsegue

我需要根据某些条件将bool值发送到第二个viewController。 但在Second ViewController中,bool变量的值始终为false。 这是第一个ViewController代码:

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}
@IBAction func moveTo(_ sender: Any) {
    self.performSegue(withIdentifier: "Move2", sender: self)

}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    if segue.identifier == "Move2"
    {
        let secondVC = segue.destination as? SecondViewController
        secondVC?.second = true

    }
}
  override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
      // Dispose of any resources that can be recreated.
  }
}

SecondViewController代码是

import UIKit

class SecondViewController: UIViewController {
var second = Bool()

override func viewDidLoad() {
    super.viewDidLoad()
    print(second)
    // Do any additional setup after loading the view.
}

但是这个第二个变量的值是假的。

我的代码错了。需要帮忙。 TIA ..

编辑:在两个ViewController中我都有导航控制器。这个问题。 SecondVC是SecondViewController的导航控制器,因此我无法将数据传递给第二个VC。

2 个答案:

答案 0 :(得分:1)

转到故事板并选择SecondViewController(左上角的黄色圆圈。转到身份检查器并从类下拉列表中选择SecondViewController。

见下图:

enter image description here

答案 1 :(得分:0)

保持简洁:

FirstVC:

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        if segue.identifier == "Move2"
        {
            let secondVC = segue.destination as? SecondViewController
            secondVC.second = true

        }
    } 

SecondVC:

class SecondViewController: UIViewController {
    var second: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
        print(second)
    }  
}  

我自己测试了一下。打印true