하나의 객체가 처리해야할 일 중 일부를 다른 객체에게 넘기는 것 ( 위임 )
TextField를 수정하기 시작하면 TextField가 노랑색으로 바뀐다
Delegate Pattern
( textField를 사용하는 class는 ViewController일 때 )
- 하나의 객체가: TextField
- 처리해야할 일 중 일부: TextField를 수정하기 시작하는 것을 감지
- 다른 객체: ViewController
- 에게 넘기는 것
textField 객체가 ViewController를 대리자로 임명
textField.delegate = self
대리자는 일을 수행하기 위해 그 기능이 정의되어 있는 프로토콜을 채택
// 채택할 프로토콜: UITextFieldDelegate
class ViewController: UIViewController, UITextFieldDelegate {
UITextFieldDelegate에서 원하는 기능을 골라서 쓴다
https://developer.apple.com/documentation/uikit/uitextfielddelegate
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.backgroundColor = .yellow
}
전체 코드: https://github.com/ddudios/Velog/blob/main/DelegatePattern/DelegatePattern/ViewController.swift
extension으로 코드 정리:
https://github.com/ddudios/Velog/blob/main/DelegatePatternExtension/DelegatePattern/ViewController.swift
직접 Delegate Pattern을 구현해보기:
https://github.com/ddudios/Velog/blob/main/DelegatePattern/DelegatePattern.playground/Contents.swift
결합도를 낮추면서 필요한 기능을 사용할 수 있다
객체간 data 전달할때 사용하기 좋다