Skip to content

Instantly share code, notes, and snippets.

@christopherkarani
Last active November 1, 2017 20:08
Show Gist options
  • Save christopherkarani/706acf02e0c8d740741a52a24376c0ed to your computer and use it in GitHub Desktop.
Save christopherkarani/706acf02e0c8d740741a52a24376c0ed to your computer and use it in GitHub Desktop.
Functionality for moving a textview Up or down in relation to the Keyboard
extension ChatController {
func setupKeyboardObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillShow(withNotification:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillHide(withNotification:)), name: .UIKeyboardDidHide, object: nil)
}
@objc func handleKeyboardWillShow(withNotification notification: Notification) {
let keyboardFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue
let keyboardDuration = (notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as AnyObject).doubleValue
containerViewBottomAnchor?.constant = -(keyboardFrame?.height)! // bottomAnchor + constant
UIView.animate(withDuration: keyboardDuration!) {
self.view.layoutIfNeeded()
}
}
@objc func handleKeyboardWillHide(withNotification notification: Notification) {
let keyboardDuration = (notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as AnyObject).doubleValue
containerViewBottomAnchor?.constant = 0
UIView.animate(withDuration: keyboardDuration!) {
self.view.layoutIfNeeded()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment