Custom Protocol and Delegate

Custom protocols and delegate is the very efficient way to passing values to other controller from one controller. If we required pass the value for only one controller in entire project the we should not go for declaring “Global Variable” to pass the values.



Example:  Display PopOver for option selection on button click event which placed on TableViewCell. On option selection make some changes on TableView.



Let’s assume ViewController of tableview is (VC-1) andViewController of  PopOver is (VC-2).

Here the actual process of CODING get started,

create one table view with custom cell on (VC-1) then design for PopOver/ popUp on (VC-2).

Now we have to pass value from  (VC-2) to  (VC-1) so create custom protocol and delegate on  (VC-2) as below

protocol popOverListViewControllerDelegate {

    func getSelectedValueFromPopOverList(str:String)

}

place this above code outside the block of class.

Now declare a variable of delegate inside (VC-2) as below

var delegate : popOverListViewControllerDelegate?

go to option selection event on (VC-2) ie. didSelect method of  popOver table and copy the below code.

this line of code will pass the value to (VC-1)

delegate?.getSelectedValueFromPopOverList(str: arrOptions[indexPath.row])

here is the end of Custom Protocol and Delegate declaration. Let us move to (VC-1) to write the further code.

First of all import the protocol popOverListViewControllerDelegate in (VC-1).

It’s  time to set the delegate, to set the delegate create an instance of (VC-2) and set the delegate as below

let popController = UIStoryboard(name: “Main”, bundle: nil).instantiateViewController(withIdentifier: “popListViewController”) as! popListViewController

  popController.delegate = self

Finally we will get the value which was passed by (VC-2) to (VC-1) using below code.

below code is the actual definition of the delegate which we created/declared in  (VC-2)

func getSelectedValueFromPopOverList(str:String)  {

    print(“I got value which is passed from(VC-2) : \(str)”)

}

 

Here is the Demo Project for this tutorial #HaveFun 🙂

 

 

 


Need more help?

Hi there, was your problem or query resolved? If not & need more assistance, please do reach out to us at info@nanostuffs.com, we'll be more than delighted to help. Nanostuffs has 7+ years of extensive Salesforce & iOS/Android experience.
Holler Box