Swift > 4.++
You can use protocol & protocol extension .
Let's create KeyboardListener Protocol
protocol KeyboardListener: class {
func registerKeyboardObserver()
func keyboardDidUpdate(keyboardHeight: CGFloat)
func removeObserver()
}
Then create @objc function into UIViewController extension
extension UIViewController {
@objc func adjustForKeyboard(notification: Notification) {
guard let keyboardValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
let keyboardScreenEndFrame = keyboardValue.cgRectValue
let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)
if notification.name == UIResponder.keyboardWillHideNotification {
if let keyboardLister = self as? KeyboardListener {
keyboardLister.keyboardDidUpdate(keyboardHeight: .zero)
}
} else {
if let keyboardLister = self as? KeyboardListener {
keyboardLister.keyboardDidUpdate(keyboardHeight: keyboardViewEndFrame.height - view.safeAreaInsets.bottom)
}
}
}
}
Then, use Keyboard listener extension for default implementations
extension KeyboardListener where Self: UIViewController {
func registerKeyboardObserver() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillHideNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
}
func removeObserver() {
NotificationCenter.default.removeObserver(self)
}
}
Finally , we can use it from our ViewController class
extension EditProfileVC: KeyboardListener {
func keyboardDidUpdate(keyboardHeight: CGFloat) {
//update view when keyboard appear,
}
}
And call register from viewwillAppear & removeObserver from deinit
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
registerKeyboardObserver()
}
deinit {
removeObserver()
}
#selector(ViewController.keyBoardUp(notification:))
and function tofunc keyBoardUp( notification: Notification){ print("HELLO") }
– Spaetzle