-3

Say I have two screens. Screen A has a picker and a button, which triggers a segue to screen B, which displays some content depending on the option selected by the picker.

How do I have the information as to what picker was selected in A, passed to B? So far, I have A doing:

@IBAction func pickThing(_ value: Int) {
    self.thing = value;
}

Which seems to work; I believe that it is detecting the value and storing it. However, when I try adding @IBOutlet weak var thingLabel: WKInterfaceLabel! to match the label in B, I can only set the value of it when the app first loads.

If I put self.thingLabel.setText("test") in the awake() function, it sets the label to "test", so that works. But changing it to self.thingLabel.setText("thing \(self.thing)") doesn't work - it sets it to whatever self.thing is initialized as, but doesn't change it later. So awake() is not the right method to use. I've also tried putting it in willActivate and in pickThing, but neither of them did anything.

Is there some method that gets called when a screen is switched to? If not, how can I send data from one screen to the next?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Benubird
  • 18,551
  • 27
  • 90
  • 141

2 Answers2

0

For example on ViewController A use this function

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? ViewControllerB {
        vc.thing = self.thing
    }
}

Or you can use closures in same methods and callback change from B ViewController on A

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let vc = segue.destination as? ViewControllerB {
            vc.clouser = { [weak self] thingB in 
                guard let `self` = self else { return }
                self.thing = thingB
            }
        }
    }
Maxim Zakopaylov
  • 546
  • 2
  • 5
  • 23
0

You need to make a variable in view controller B titled something like "parentVC," which would be of view controller A's class. In view controller A's class, you need to call prepare(for segue UIStoryboardSegue, sender: Any?). In this method, you can access the segue's destination property, which would be view controller B. From here you can set view controller B's "parentVC" property to "self," i.e. view controller A. Then in view controller B's class you can access properties of view controller A by using the "parentVC" variable. The code in view controller A's class would look something like this:

func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.destination is ViewControllerB {
        let viewControllerB = segue.destination as? ViewControllerB
        viewControllerB.parentVC! = self
    }

}
David Chopin
  • 2,780
  • 2
  • 19
  • 40