Swift Delegate Protocal Pattern

Swift Delegate Protocol Pattern

The delegate and protocal pattern is a one-to-one communication pattern in Swift that allows one view to communicate with another view.

Example

The view controller in the bottom sheet is communicating with the main view controller. It’s communicating when the button is tapper, the main view controller wil update the UI.

Example

Delegate

Basically a delegate is sitting back waiting to be told when and what to do. We don’t call delegate methods themselves, they get called automatically when they are told what to do. Take a boss and an intern as an analogy. The production selection view controller is goint to tell the main view controller what to do, the production selection view controller has all the information, it knows what was tapped and it has to pass that message along to the main view controller.

Analogy

In the product selection view controller which is goint to be the boss in this case, we need to create a protocol. It is a list of commands. It is like the job description.

1
2
3
protocol ProductSelectionDelegate {
func didSelectProduct(name: String, imageName: String)
}

We also need to have a quote intern on the product selection screen. Set a variable called delegate and that is of type ProductSelectionDelegate, it is like a job position.

1
var delegate: ProductSelectionDelegate?

Now go to the main view controller and apply for the job. To to that, we need to confrom to the product selection delegate.

1
class ViewController: UIViewController, ProductSelectionDelegate

Now that we have signed up for the job, we need to do something when we get told what to do this job.

1
2
3
4
func didSelectProduct(name: String, imageName: String) {
productNameLabel.text = name
productImageView.image = UIImage(named: imageName)
}

Now the main view contrller should be saying “sign me up, I want to be your delegate, I want to be your intern”.

1
2
let destinationVC = ProductSelectionVC()
destinationVC.delegate = self

Finally, the product selection view controller in this case the boss is to give the order to do the job. The boss is saying “Do your job delegate and here is the iformation you need to do your job”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@objc func iPhoneButtonTapped() {
delegate?.didSelectProduct(name: "iPhone 14", imageName: "iphone")
dismiss(animated: true)
}

@objc func iPadButtonTapped() {
delegate?.didSelectProduct(name: "iPad Air", imageName: "ipad")
dismiss(animated: true)
}

@objc func macBookButtonTapped() {
delegate?.didSelectProduct(name: "MacBook", imageName: "mac")
dismiss(animated: true)
}


Swift Delegate Protocal Pattern
http://example.com/2024/08/13/Swift-Delegate-Protocal-Pattern/
Author
Huajing Lu
Posted on
August 13, 2024
Licensed under