Search code examples
xcodeswiftviewxcode6segue

Passing data from textfield to next view


I am trying to develop a basic app in Xcode 6.1 and Swift language.

I cant seem to find any IOS 8, Xcode6 and Swift resources yet that help with this. Everything is still xcode 5 and IOS 7.

I have the whole story board done with images buttons and segues. just need to script it.

There are 6 segues all with segue "show".

I am just trying to capture one text field per view controller. upon button press for the segue to the next view controller.

the prepareForSegue thing confuses me.

how do I capture the data from a text field save it to a variable on button press and send that variable info to the next view controller?

That text field I want saved to a variable or let that I can have the final view controller access all the data input from each view controller and then do some basic math.

Any body can help with this?


Solution

  • Assuming that you have two view Controllers here is how you will pass value to the second view controller.

     class ViewControllerA: UIViewController {
          @IBOutlet var textField: UITextField = nil
    
          ...
    
          override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
                 if (segue.identifier == "segueTest") {
                     var svc = segue!.destinationViewController as ViewControllerB;
                     svc.passedValue = textField.text
                 }
          }
     }
    
     class ViewControllerB: UIViewController {
         var passedValue: String?
         ... 
         override func viewDidLoad() {
              ...
              if let myPassedData = passedValue {
                   println(myPassedData)
              }
    

    or use

                 let myPassedData = passedValue ?? "" 
                   println(myPassedData)
              }
         }
     }