Created
June 4, 2023 07:52
-
-
Save MickhailP/cbb4dd697d59a6520a0fd7746d14b616 to your computer and use it in GitHub Desktop.
KeyboardAvoidance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension ViewController { | |
private func setNotificationForKeyboardAppearance() { | |
NotificationCenter.default.addObserver( | |
self, | |
selector: #selector(self.keyboardWillShow), | |
name: UIResponder.keyboardWillShowNotification, | |
object: nil) | |
NotificationCenter.default.addObserver( | |
self, | |
selector: #selector(self.keyboardWillHide), | |
name: UIResponder.keyboardWillHideNotification, | |
object: nil) | |
} | |
@objc func keyboardWillShow(_ notification: NSNotification) { | |
if let chatViewBottomConstraint { | |
moveViewWithKeyboard(notification: notification, viewBottomConstraint: chatViewBottomConstraint, keyboardWillShow: true) | |
} | |
} | |
@objc func keyboardWillHide(_ notification: NSNotification) { | |
if let chatViewBottomConstraint{ | |
moveViewWithKeyboard(notification: notification, viewBottomConstraint: chatViewBottomConstraint, keyboardWillShow: false) | |
} | |
} | |
func moveViewWithKeyboard(notification: NSNotification, viewBottomConstraint: NSLayoutConstraint, keyboardWillShow: Bool) { | |
guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue) else { return } | |
let keyboardHeight = keyboardSize.cgRectValue.height | |
let keyboardDuration = notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! Double | |
let keyboardCurve = UIView.AnimationCurve(rawValue: notification.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as! Int)! | |
if keyboardWillShow { | |
let safeAreaExists = (self.view?.window?.safeAreaInsets.bottom != 0) | |
let bottomConstant: CGFloat = 20 | |
#warning (" CHANGE THE BOTTOM CONSTRAINT HERE ") | |
chatViewBottomConstraint?.constant = -(keyboardHeight + (safeAreaExists ? 0 : bottomConstant)) | |
} else { | |
chatViewBottomConstraint?.constant = -20 | |
} | |
let animator = UIViewPropertyAnimator(duration: keyboardDuration, curve: keyboardCurve) { [weak self] in | |
self?.view.layoutIfNeeded() | |
} | |
animator.startAnimation() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment