Modifying and Using Variables Across Files in Swift 4

I have two View Controllers. In the first one, let's call it ViewControllerA, I have a Button. In the second view controller, let's call it ViewControllerB, I have a View. The Button in ViewControllerA performs a segue to ViewControllerB. Normally, the View in ViewControllerB has its isHidden property set to true.

How do I make it so when I click the Button in ViewControllerA, the View in ViewControllerB has its isHidden property changed to false?

This is what I have for ViewControllerA

class ViewControllerA: UIViewController {

var buttonPressed : Bool = false

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

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

@IBAction func theButton(_ sender: Any) {
    buttonPressed = true

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

}

And this is what I have for ViewControllerB:

class ViewControllerB: UIViewController {

@IBOutlet weak var myView: UIView!

var isButtonPressed : Bool = ViewControllerA().buttonPressed


override func viewDidLoad() {
    super.viewDidLoad()

    if isButtonPressed == true {

        myView.isHidden = false
    }
    else {

        myView.isHidden = true
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}


}

2 answers

  • answered 2018-03-13 21:27 Javier Cancio

    Just override prepare(for:sender:) in your ViewControllerA like this:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard segue.identifier == "goToControllerB", let destination = segue.destination as? ViewControllerB else { return }
    
        destination.isButtonPressed = true
    }
    

    Then, inside viewDidLoad() function in your ViewControllerB, set visibility of the view:

    myView.isHidden = !isButtonPressed
    

  • answered 2018-03-13 21:27 Xcoder

    Implement the prepareForSegue method in ViewControllerA like so:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
       if segue.identifier == "goToControllerB" {
           if let destinationVC = segue.destination as? ViewControllerB {
               destinationVC.isButtonPressed = false
           }
       }
    }
    

    And in ViewControllerB, change the variable:

    var isButtonPressed: Bool?