2016年4月10日 星期日

Swift passing data between two ViewControllers (protocol + delegate)


1. First view controller


import UIKit

class ViewController: UIViewController, mydelegate {

    @IBOutlet weak var txtfield: UITextField!
    
   
    func myfunc(controller: SecondViewController,
        text: String) {
            self.txtfield.text = text
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        
        
        let vc = segue.destinationViewController as! SecondViewController
        vc.data = self.txtfield.text
        vc.delegate = self
        
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
   


}


2. Second View controller


import UIKit
protocol mydelegate {
    func myfunc(controller: SecondViewController, text: String)
}

class SecondViewController: UIViewController {
   
    
    @IBOutlet weak var txtfield: UITextField!
    var delegate: mydelegate? = nil
    var data : String = ""
    
    
    @IBAction func back_touchinside(sender: AnyObject) { // Button touch inside event
        if(delegate != nil) {
           delegate!.myfunc(self, text: txtfield.text)
        }

        self.dismissViewControllerAnimated(true, completion: nil) // KEY!!!

     
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        txtfield.text = data
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}