I finally found out about the delegate, so I made a memorandum.
It is convenient to use when you want to use small parts such as buttons, but want to process differently for each page.
This time, I will use the buttons below. From the left, "Back button", "Commentary button", and "Next button". I want to use this button class on various pages.
[Thing you want to do] I want to switch the button press action for each page. When you press the back button, one page transitions to the previous screen and another page ends modal. Or for other pages, I want to save the page before closing the page. etc
[Solutions] Write a button press action on each page. The design part of the button may be shared, but the function of the action part is delegated to each page. This is the role of the delegate, which translates as "transfer."
[manner]
FooterView.swift
protocol TapLeftButtonVCDelegate {
func tapLeftButton()
}
protocol TapCenterButtonVCDelegate {
func tapCenterButton()
}
protocol TapRightButtonVCDelegate {
func tapRightButton()
}
ViewController.swift
//Since I want to use only the right button on this page, I declare only the protocol for the right button.
@IBOutlet weak var footerView: FooterView!
override func viewDidLoad() {
super.viewDidLoad()
footerView.tapRightButtonVCDelegate = self
}
extension ViewController: TapRightButtonVCDelegate {
func tapRightButton() {
//Proceed to the next screen, save process, write anything you like
}
}
class FooterView: UIView {
var tapRightButtonVCDelegate: TapRightButtonVCDelegate?
@IBAction func tapRightButton(_ sender: Any) {
tapRightButtonVCDelegate?.tapRightButton()
}
}
Now you can reuse the button on various pages.
[Impression] It was how to use the delegate considering the purpose. There may be other convenient ways to use it.
Recommended Posts