Search code examples
swiftxcodesegue

Attempting to pass data from one viewcontroller to another using segues


I have two viewcontrollers setup and set the segue connections as well. I'm attempting to pass data from one of the VC's to the other. Using the below code and using the func override works. What i want to do is only have the override func prepare fire off when a button is pressed and when i paste the override func code into a button action, it doesnt work - the label on the first VC doesnt update - it stays to the default value i set.

First ViewController code:

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

Second ViewController code:

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

Button action that ive tried

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

Solution

  • You need to trigger it with 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)
        }
    
    
    }