Search code examples
variablesswiftviewcontrollersharing

Variable Sharing


I have an app in which, when a button is pressed on an original view, another view pops up. I want, basically, to be able to grab the text from a text field in the original view, and paste it onto a label in the new view. I've seen a bunch of Obj-c answers for this, but none for swift. Thanks for you help!


Solution

  • you can use prepareForSegue for pass data from one view to another View. Here is the code for that:

    ViewController.swift

    import UIKit
    
    class ViewController: UIViewController {
    
    @IBOutlet weak var txt: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
    
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    
        if segue.identifier == "goNext" {
            let nextView :nextViewController = segue.destinationViewController as nextViewController
    
            nextView.passedData = self.txt.text
    
            }
        }
    }
    

    nextViewController.swift

    import UIKit
    
    class nextViewController: UIViewController {
    
    @IBOutlet weak var lbl: UILabel!
    var passedData = String()
    override func viewDidLoad() {
        super.viewDidLoad()
    
        self.lbl.text = self.passedData
        }
    }
    

    Here I created a sample project for you for more reference: https://github.com/DharmeshKheni/pass-Data-with-prepareForSegue-in-swift