Search code examples
swiftuiviewcontrollersegue

SWIFT - Variable resetting when back from second ViewController


I have been searching for hours here and Google but still didn't find the answer. Everything point to passing variable from a VC to an other but not how to keep variables alive on the VC.

I can pass variables from a VC to an other using multiple methods such as singleton but when I go from second VC to the main VC I'm still facing the same problem.

Exemple you have the main VC which have a label and 2 buttons. When you click one of the button the label text change and then you click the second button to Segue to the second VC. Then when you comeback to the first VC the problem appear: the label is reseted to it's initial text "label". Why?

I tried using global variable in a separate swift file. I said to myself well the value is stored in an other swift file there is no reason why the value of the label reset.. but well it's still resetting.

Thanks so much.

Example in video: https://youtu.be/Wx5blkQqU7E

Very basic example:

varTest.swift

import Foundation

var myVar2: String!

Main ViewController

import UIKit

class ViewController: UIViewController {

    @IBOutlet var mylabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

    @IBAction func dsfg(_ sender: UIButton) {

        performSegue(withIdentifier: "switchForm", sender: self)
    }

    @IBAction func changeLabeltext(_ sender: UIButton) {


        myVar2 = "Good."
        mylabel.text = myVar2

    }
}

Second ViewController

import UIKit

class ViewController2: UIViewController {


    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func btnPrint(_ sender: UIButton) {

        performSegue(withIdentifier: "returnForm", sender: self)
    }
}

Solution

  • I think the problem is that you are not returning back from ViewController2 to ViewController, but you are pushing a new ViewController instance, which will display a new UILabel with its default value. You can create an unwind segue from your second view controller to the first view controller, or you can call dismiss(animated:completion:) on the second view controller. This article can guide you to create an unwind segue.