Delegates Example in swift 4 | Pass Data with Delegation - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

19 Oct 2017

Delegates Example in swift 4 | Pass Data with Delegation

Delegates are a design pattern that allows one object to send messages to another object when a specific event happens.

Delegate helps in passing data back from presented view controller(SecondVC) to presenting view controller(FirstVC).

How Delegates Work?  Swift

Imagine an object X calls an object Y to perform an action. Once the action is complete, object X should know that Y has completed the task and take necessary action, this can be achieved with the help of delegates!

For better understanding of delegate we will go through sample application in swift, download or clone the starter project.

Build and Run we will see the following:

Delegates Example in swift 4 Starter

Here we are having FirstVC and SecondVC. FirstVC having quote and SecondVC is for changing the quote in FirstVC.

But now on tapping save button in SecondVC, the quote in FirstVC is not changing.

The problem is that this views are part of class Y and have no idea about class X, so we need to find a way to communicate between this two classes, and that’s where delegation helps.

We will follow step by step procedure to achieve delegation.

Step 1:

Open SecondVC and add the following protocol:

protocol SecondVCDelegate: class {
    func changeQuote(_ text: String?)
}

Here we are declaring only one method that accepts an optional String as an argument based on our requirement.

Step 2:

Create delegate property as follow:

weak var delegate: SecondVCDelegate?

Here we created a delegate property of protocol type and it should be optional.

Step 3:

Add the following line of code in saveQuote() method:

delegate?.changeQuote(textView.text)

Step 4:

Now open FirstVC and conform the protocol as following:

class FirstVC: UIViewController,SecondVCDelegate {

/......

Step 5:

Add the following method:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let nav = segue.destination as? UINavigationController, let secondVC = nav.topViewController as? SecondVC {
        secondVC.delegate = self
    }
}

Here we are just creating an instance of SecondVC and assign its delegate to self, but what is self here? well, self is the FirstVC which has been delegated!

Step 6:

Finally add the function of the SecondVCDelegate protocol:

func changeQuote(_ text: String?) {
    quoteLabel.text = text
}

Build and Run , now we can change quote by using delegation.

 Delegates Example in swift 4 Final

Great you just completed delegations in swift.

Download sample project with examples :


1 comment:

Post Top Ad