Friday, 6 January 2017

Data Pass One View to Another in Swift

Pass Information Forward From One ViewController to 

Another in Swift



** Write in ViewController.swift



import UIKit
class ViewController: UIViewController {
    
    @IBOutlet weak var myTextField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    @IBAction func addButtonClicked(_ sender: UIButton){
        
        // Check if value from myTextField is not empty
        if myTextField.text?.isEmpty == true
        {
            return
        }
        
        // Instantiate SecondViewController
        let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
        
        // Set "Hello World" as a value to myStringValue
        secondViewController.myStringValue = myTextField.text
        
        // Take user to SecondViewController
        self.navigationController?.pushViewController(secondViewController, animated: true)
        
    }
   

}


** Write in SecondViewController.swift



import UIKit

class SecondViewController: UIViewController {

    var myStringValue:String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // We will simply print out the value here
        print("The value of myStringValue is: \(myStringValue!)")
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */


}





No comments:

Post a Comment