Skip to content

Instantly share code, notes, and snippets.

@yashthaker7
Last active May 30, 2022 12:10
Show Gist options
  • Save yashthaker7/fe0604a0f1c838a464ef39cef17f09d7 to your computer and use it in GitHub Desktop.
Save yashthaker7/fe0604a0f1c838a464ef39cef17f09d7 to your computer and use it in GitHub Desktop.
Keyboard observer for your chat view to change y position.
// how to use
// call addKeyboardObserver() in viewWillAppear
// call removeKeyboardObserver() in viewDidDisappear to prevent memory leak
// override changeKeyboardFrame function in viewController
extension UIViewController {
func addKeyboardObserver() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
func removeKeyboardObserver() {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc internal func keyboardWillShow(_ notification: Notification) {
adjustingHeight(true, notification: notification)
}
@objc internal func keyboardWillHide(_ notification: Notification) {
adjustingHeight(false, notification: notification)
}
internal func adjustingHeight(_ show: Bool, notification: Notification) {
guard let userInfo = notification.userInfo else { return }
let keyboardFrame: CGRect = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let animationDurarion = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval
changeKeyboardFrame(keyboardFrame, keyboardAnimationDuration: animationDurarion, isKeyboardShow: show)
}
@objc func changeKeyboardFrame(_ keyboardFrame: CGRect, keyboardAnimationDuration: TimeInterval, isKeyboardShow: Bool) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment