-4

i'm currently developing an app in which the user enters a number in an UIText field and I want to store that number and reuse it in another view controller example:

FirstVC <--- the user types the number on an UIText Field

a Button is tapped on the FirstVC to take the user to a SecondVC

SecondVC <-- the number can be called and can be displayed on a label

Can someone explain me how to store the number and then call it and display it later?

St33v3n
  • 39
  • 2
  • Why not reverse the logic? Pass the variable from the first VC - where the job is to *get* a valid number - to the second VC - where the job is to *display* it? That's the way most would think to do it. –  Mar 04 '17 at 19:59
  • The thing is that I also need to use the number to make an equation, I need to display the typed number and use it on the equation – St33v3n Mar 04 '17 at 20:30
  • Still, the usual flow of things is (a) the first VC has a job of some sort... say, get user input of some sort... followed by (b) a second view - with associated VC - that has it's job of some sort... say display a number and do computations on it. It's your basic MVC model. Once that second VC is in control, the first VC is either deallocated or buried in the stack beneath the current view and VC. Virtually everything in Xcode (be it Swift or Obj-C) is geared to this. No need to *fight* it - learn it! –  Mar 04 '17 at 20:37
  • Addition to that comment. Set up a public *var* for the number in the second VC. Learn how to do a segue. Pass the number in *prepare(for Segue:)* to the second VC. At that point you have *everything* in the second VC you need - the var is there, you can display it, do some calculations on it, pass it (forward or back) to another view or VC.... –  Mar 04 '17 at 20:39
  • Possible duplicate of [Passing Data between View Controllers](http://stackoverflow.com/questions/5210535/passing-data-between-view-controllers) – dandan78 Mar 04 '17 at 23:26

1 Answers1

1

First you setup the segue,

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "yourSegue" {
        if let viewController = segue.destinationViewController as? your view controller type {
            //for example
           viewController.text = text
        }

    }
}

then in your button or whatever you want,

performSegue(withIdentifier: "yourSegue", sender: sender)
K-2SO
  • 233
  • 1
  • 12