UITableViewDelegate, UICollectionViewDelegate 등 대부분의 UIKit 컴포넌트에서 사용// 1. 프로토콜 정의
protocol CustomViewDelegate: AnyObject {
func didTapButton()
}
// 2. 위임 객체에서 delegate 프로퍼티 선언
class CustomView: UIView {
weak var delegate: CustomViewDelegate?
func buttonTapped() {
delegate?.didTapButton()
}
}
// 3. 위임을 받는 쪽에서 프로토콜 구현
class ViewController: UIViewController, CustomViewDelegate {
let customView = CustomView()
override func viewDidLoad() {
super.viewDidLoad()
customView.delegate = self
}
func didTapButton() {
print("버튼이 눌렸습니다!")
}
}
weak으로 선언해 메모리 누수 방지AnyObject를 붙이면 클래스 타입에서만 사용 가능 (ARC 적용 가능)Delegate 패턴은 iOS 개발에서 필수로 알아야 할 설계 방식입니다. 직접 프로토콜을 선언하고, delegate를 연결하고, 동작을 구현하면서 익혀나가는 것이 중요합니다.