jonjamster
3/28/2018 - 9:00 PM

Passing data forward and backwards using delegates and protocols

//
//  ViewController.swift
//  Segues 2
//
//  Created by John on 27/03/2018.
//  Copyright © 2018 Rom and Ram. All rights reserved.
//

import UIKit

class FirstViewController: UIViewController, CanReceive {
    
    var dataPassedBack = ""
    

    @IBOutlet weak var label: UILabel!
    
    
    

    
    
    
    @IBOutlet weak var textField: UITextField!
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        
        
        label.text = dataPassedBack
        
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    
    
    
    @IBAction func sendButtonPressed(_ sender: Any) {
        
        performSegue(withIdentifier: "sendDataForwards", sender: self)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "sendDataForwards" {
        
        let secondVC = segue.destination as! SecondViewController
        
        secondVC.data = textField.text!
            
        secondVC.delegate = self
        
    }
    
}
    func dataReceived(data: String) {
        label.text = data
    }
    
    
    
}








------------------------



//
//  SecondViewController.swift
//  Segues 2
//
//  Created by John on 27/03/2018.
//  Copyright © 2018 Rom and Ram. All rights reserved.
//

import UIKit

protocol CanReceive {
    
    func dataReceived(data: String)
}

class SecondViewController: UIViewController {
    
    var delegate : CanReceive?
    
    var data = ""
    
    @IBOutlet weak var textField: UITextField!
    
    
    @IBOutlet weak var label: UILabel!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        label.text = data
        
        

        // Do any additional setup after loading the view.
    }

    
    
  
    
    

    @IBAction func sendDataBack(_ sender: Any) {
        
        delegate?.dataReceived(data: textField.text!)
        dismiss(animated: true, completion: nil)
        }
    }