UIKit
Notification Center
데쿠!
2020. 7. 4. 18:32
Notification Center는 객체들이 서로 상호작용할 수 있도록 하는 방법입니다.
다시 말하면, 특정 객체가 Notification Center에 등록된 event를 발생시키면 해당 event를 처리할 것이라고 등록된 observer들이 event에 대한 행동을 취하는 것이 Notification 이 동작하는 방식입니다.
keyboard를 예로 들자면
1. 먼저 event를 발생시키는 객체에서 event를 Notification Center에 등록합니다.
2. event를 실행할 객체에서 observer로 등록합니다.
override func viewWillAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardwillhide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
-> 특정 객체인 UIResponder.keyboardWillShowNotification의 event를 실행할 객체의 viewWillAppear함수에 observer로 등록합니다.
-> view가 모두 나타나기 전에 selector 함수를 실행시킵니다.
3. 만약 다른 view로 이동할 때, observer를 삭제하고싶다면
override func viewWillDisappear(_ animated: Bool){
NotificationCenter.default.removeObserver(self)
}
-> removeObserver를 추가해줍니다.
출처 및 참고 : baked-corn.tistory.com/42