我有两个viewcontrollers设置,并设置segue连接。我正试图将数据从一个VC传递到另一个VC。使用下面的代码和func override可以工作。我要做的只是在按下按钮时关闭override func prepare fire,当我将override func代码粘贴到按钮操作中时,它不起作用-第一个VC上的标签不更新-它保持为我设置的默认值。
第一个视图控制器代码:

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

最佳答案

你需要用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)
    }


}

10-06 09:32