The Notification Center in iOS is a system that allows apps to observe (listen to) events happening in the system or app, such as keyboard appearance and disappearance.
👉 In simple terms: It lets your app know when the keyboard shows, hides, or changes size.
iOS provides predefined notifications for keyboard events:
| Notification | Meaning |
|---|---|
keyboardWillShow |
Keyboard is about to appear |
keyboardDidShow |
Keyboard has appeared |
keyboardWillHide |
Keyboard is about to disappear |
keyboardDidHide |
Keyboard has disappeared |
keyboardWillChangeFrame |
Keyboard size/position changing |
Keyboard Event → Notification Center → Observer (ViewController) → Action
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillShow),
name: UIResponder.keyboardWillShowNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillHide),
name: UIResponder.keyboardWillHideNotification,
object: nil)
}
@objc func keyboardWillShow(notification: Notification) {
print("Keyboard is shown")
}
@objc func keyboardWillHide(notification: Notification) {
print("Keyboard is hidden")
}
Sometimes we need keyboard height to adjust UI.
@objc func keyboardWillShow(notification: Notification) {
if let userInfo = notification.userInfo,
let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
let keyboardHeight = keyboardFrame.height
print("Keyboard height: \(keyboardHeight)")
}
}
Draw:
Keyboard Appears
↓
NotificationCenter sends event
↓
ViewController receives notification
↓
Adjust UI / Move TextField
Problem:
Solution:
@objc func keyboardWillShow(notification: Notification) {
if let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
self.view.frame.origin.y = -keyboardFrame.height / 2
}
}
@objc func keyboardWillHide(notification: Notification) {
self.view.frame.origin.y = 0
}
Always remove observers to avoid memory issues:
deinit {
NotificationCenter.default.removeObserver(self)
}
viewDidLoad()deinitNotification Center detects system events
Used for keyboard tracking in apps
Key notifications:
Steps:
Used in chat apps, forms, login screens
Open this section to load past papers