尝试使用Segues将数据从一个ViewController传递到另一个ViewController

时间:2019-06-16 14:05:37

标签: swift xcode segue

我有两个ViewController设置并设置了segue连接。我正在尝试将数据从一个VC传递到另一个。使用下面的代码并使用func覆盖起作用。我想做的是仅在按下按钮时将覆盖功能准备就绪,并且将覆盖功能代码粘贴到按钮操作中时,它不起作用-第一个VC上的标签不更新-保持默认值我设定的值。

第一个ViewController代码:

    var testLabel1:String = "default"

    @IBOutlet weak var testLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        testLabel?.text = testLabel1
        // Do any additional setup after loading the view.
    }

第二个ViewController代码:

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        if segue.destination is ViewController
        {
            let vc = segue.destination as? ViewController
            vc?.testLabel1 = "Success"
        }
    }
我尝试过的

按钮操作

    @IBAction func actionBtn(_ sender: Any) {
        func prepare(for segue: UIStoryboardSegue, sender: Any?)
        {
            if segue.destination is ViewController
            {
                let vc = segue.destination as? ViewController
                vc?.testLabel1 = "Success"
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

您需要使用performSegue

触发它
class FirstVc:UIViewController {

    @IBOutlet weak var lbl:UILabel!

    @IBAction func goToSecond(_ sender: Any) {
        self.performSegue(withIdentifier:"YourSegueName",sender:nil)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "YourSegueName" {
            let vc = segue.destination as! SecondVC
            vc.testLabel1 = "Success"
        }
    }

    func setData(_ str:String){
        self.lbl.text = str

    }

}

class SecondVC:UIViewController {

    var testLabel1 = ""
    weak var delegate:FirstVc?

    func goBack() {
        self.delegate?.setData("FromSecond")
        self.dismiss(animated: true, completion: nil)
    }


}