Set up a simple delegate to communicate between two view controllers in iPhone

In this article, you learn about delegates and creating delegates. First of all,

What’s a delegate?

Delegate is a simple term that refers to communication between objects. It is a simple way of connecting objects and communication between them.

How does delegate work?

A delegate is created with help of protocol. A protocol is declared in class, inside which some event will happen, that should notify other classes. In protocol we write the declaration of function and it is defined inside the calling class.

How to create a delegate?

We’ll do this with help of an example project.

Steps to perform −

  • Create a class, name it as FirstViewController, create another class and call it SecondViewController. Create their respective View controllers in the storyboard.

  • Declare a protocol in SecondViewController, A protocol is declared outside any class or other objects.

protocol SecondViewControllerDelegate {
   func buttonPressedInVC2()
  • In the SecondViewController, Create an optional object of the delegate we just created,

var delegate: SecondViewControllerDelegate?
  • We need to call the function declared in protocol, when some event happens in SecondViewController, let’s create an event that happens when a button is pressed in second view controller.

@IBAction func buttonTapped(_ sender: UIButton) {
   self.navigationController?.popViewController(animated: true)

This is all required in SecondViewController, now let’s work on FirstViewController.

  • We need to conform/ implement the FirstViewController to SecondViewControllerDelegate, and it will automatically ask you to add protocol stubs.

extension FirstViewController: SecondViewControllerDelegate {
   func buttonPressedInVC2() { }
  • Inside the protocol we just implemented we should write the code we want to execute when this delegate action happens.

    Let’s create a label In FirstViewController and change it’s text when delegate method Is called.

extension FirstViewController: SecondViewControllerDelegate {
   func buttonPressedInVC2() {
      self.lblOne.text = "Delegate Implemented"
  • One last step left is, that the delegate object in SecondViewController is optional and would be nil until it is assigned, So In the FirstViewController we’ll assign that object while going from FirstViewController to SecondViewController.

    Let’s create a button in FirstViewController for that.

@IBAction func goToNextVC(_ sender: Any) {
   let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
   vc.delegate = self
   self.navigationController?.pushViewController(vc, animated: true)
  • And if you didn’t realize it yet, we need to embed FirstViewController in a Navigation Controller. Let’s run the app and see how it works.

Updated on: 27-Jun-2020


Kickstart Your Career

Get certified by completing the course

Get Started