Ubaid Kolad

Software Engineer ยท April 2023

How to create our own custom delegate in Swift?

What are delegates?

Delegation (writing delegates) is a design pattern commonly used in iOS development. In this pattern, an object (the "delegate") is designated to handle specific responsibilities or provide functionality for another object. The delegation pattern is used to establish communication between objects without creating a strong coupling between them.

Let's understand with an example.

Let's say we have a view that allows the user to enter some text and we want to notify the parent view when the user taps the "Submit" button. We can use a delegate to accomplish this.
First, we need to define a protocol that our delegate will conform to. In this case, we'll call it SubmitButtonDelegate:

protocol SubmitButtonDelegate {
func submitButtonTapped()
}

This protocol defines a single method that will be called when the submit button is tapped. Next, we need to create a view that includes a submit button and a reference to our delegate:

struct SubmitButtonView: View {
var delegate: SubmitButtonDelegate?

var body: some View {
Button("Submit") {
delegate?.submitButtonTapped()
}
}
}

In this view, we define a reference to our delegate using the delegate property. The Button element calls the submitButtonTapped() method on the delegate when it is tapped.
Finally, we need to implement the SubmitButtonDelegate protocol in our parent view:

struct ParentView: View, SubmitButtonDelegate {
var body: some View {
VStack {
Text("Enter some text:")
TextField("Text", text: .constant(""))
SubmitButtonView(delegate: self)
}
}

func submitButtonTapped() {
//handle the submit button tap here
}
}

In this view, we create an instance of theSubmitButtonView and pass in a reference to self as the delegate. We also implement the submitButtonTapped()method to handle the button tap.
When the user taps the submit button, the submitButtonTapped() method will be called on the parent view, allowing us to handle the event and update the UI as needed.
That's it! This is a simple example of how to create a custom delegate in SwiftUI. The delegation pattern can be used in many different scenarios to allow communication between different parts of your app.