Passing data between ViewControllers via Delegate & Protocols Swift 4.0

Protocol :  A Protocol defines the blueprint of method , properties and other requirements for the particular task.



In this tutorial we are study to pop data from ViewController_B to ViewController_A using custom delegate. This tutorial working on Xcode 9 and Swift 4.

Protocol Define :  define the protocol in the ViewController_B Class.
protocol someDelegate {
    func valueLable(update : String)
}
ViewController_B :  In this class create object of the delegate and called the method of the protocol.
class ViewController_B: UIViewController , UITextFieldDelegate {
    var delegate : someDelegate! = nil
    @IBOutlet weak var txtField: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    @IBAction func click_Pop(_ sender: Any) {
        if (txtField.text?.characters.count)! > 0 {
            delegate.valueLable(update: txtField.text!)
            self.navigationController?.popViewController(animated: true)

        }else{
            let alertC = UIAlertController(title: "Demo", message: "Please enter text in textField.", preferredStyle: UIAlertControllerStyle.alert)
            let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
            alertC.addAction(action)
            self.present(alertC, animated: true, completion: nil)
        }
    }

ViewController_A :  Adding the protocol in the class and also define the method of protocol.

class ViewController_A: UIViewController, someDelegate {

    @IBOutlet weak var lblTitle: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func click_Push(_ sender: Any) {
        self.performSegue(withIdentifier: "second", sender: nil)
    }

    func valueLable(update : String){
        self.lblTitle.text = update
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "second" {
            let destination = segue.destination as! ViewController_B
            destination.delegate = self
        }
    }
}

OUTPUT :






Demo : Protocol-Demo

Thanks.
Passing data between ViewControllers via Delegate & Protocols Swift 4.0 Passing data between ViewControllers via Delegate & Protocols Swift 4.0 Reviewed by KIRIT MODI on 04:07:00 Rating: 5

No comments:

Powered by Blogger.