I wish to achieve keyboard and view resizing behaviour, as shown in iOS Messages. It looks something like
https://i.imgur.com/92rvHpo.mp4
I try with the following
Step 1
This ensures when our scroll down gesture hit the keyboard region, and keyboard will scroll down along with our gesture action.
collectionView.keyboardDismissMode = .interactive
Step 2
Adjust the bottom constraint, to ensure our collection view doesn't visually blocked by the keyboard. We adjust the bottom constraint when the keyboard finishes hiding, or keyboard finishes showing.
override func viewDidLoad() {
super.viewDidLoad()
initKeyboardNotifications()
}
//
// https://stackoverflow.com/a/41808338/72437
//
func initKeyboardNotifications() {
// If your app targets iOS 9.0 and later or macOS 10.11 and later, you do not need to unregister an observer
// that you created with this function.
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 private func keyboardWillShow(sender: NSNotification) {
let i = sender.userInfo!
let s: TimeInterval = (i[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let k = (i[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
bottomLayoutConstraint.constant = -k
UIView.animate(withDuration: s) { self.view.layoutIfNeeded() }
}
@objc private func keyboardWillHide(sender: NSNotification) {
let info = sender.userInfo!
let s: TimeInterval = (info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
bottomLayoutConstraint.constant = 0
UIView.animate(withDuration: s) { self.view.layoutIfNeeded() }
}
This is our imperfect outcome so far.
I guess, I need to adjust the bottom constraint real-time, when keyboard is being dragged. But, I have no idea from where I can get the keyboard height information, when it is being dragged.
Do you have any idea, how I can adjust the bottom constraint real-time, when keyboard is being dragged?