Delegate란?
어떤 객체가 해야 하는 일을 부분적으로 확장해서 다른 객체가 대신 처리를 한다.
Delegate 패턴을 사용하는 이유
객체가 어떤 일을 처리하기에는 부담스러워 처리해야 할 일 중 일부를 다른 객체에게 넘기기 위해서
사용 방법
1. Delegate 채택 (프로토콜 채택)
class ViewController: UIViewController, UITableViewDelegate {
// ...
}
또는
class ViewController: UIViewController {
// ...
}
extension ViewContoller: UITableViewDelegate {
}
(extension을 사용해서 UITableViewController 채택)
2. 위임자 설정
class ViewController: UIViewController, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView! // 추가
override func viewDidLoad() {
super.viewDidLoad()
}
tableView.delegate = self // 추가
}
tableView.delegate = self 에서 self는 현재 클래스인 ViewController. (ViewController가 위임자)
-> tableView의 일을 ViewController가 대신하기로 위임
3. delegate의 메서드 구현
특정 이벤트가 발생됐을 때 호출될 메서드를 구현하면 된다.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let VC: NextViewController = self.storyboard?.instantiateViewController(withIdentifier: "NextViewController") as? NextViewController else { return }
VC.modalPresentationStyle = .overFullScreen
present(VC, animated: true, completion: nil)
}
tableView의 cell을 클릭하면 뷰 이동
'Language > Swift' 카테고리의 다른 글
iOS - App 생명주기 (0) | 2022.11.05 |
---|---|
iOS - AppDelegate, SceneDelegate (0) | 2022.11.05 |
iOS - Singleton Pattern (0) | 2022.11.01 |
iOS - GCD(Grand Central Dispatch) (1) | 2022.11.01 |
iOS - Sync, Async, Serial, Concurrent (1) | 2022.10.31 |
Comment