I have a UIView
container which holds a UITextField
and two UIButtons
(see image below).
I have written an extension
which listens to a UIKeyboardWillShow
notification and animates the UIView
so that it binds to the keyboard when it shows.
This works perfectly, but as soon as I start typing the UIView
disappears again.
Extension usage:
sendMessageView.bindToKeyboard()
UIView extension:
extension UIView {
func bindToKeyboard() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}//end func
@objc func keyboardWillShow(notification: NSNotification) {
let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
let beginningFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let endFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let deltaY = endFrame.origin.y - beginningFrame.origin.y
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
self.frame.origin.y += deltaY
}, completion: nil)
}//end func
}//end extension
UIView binds to keyboard when it is displayed:
UIView disappears (I suspect behind the keyboard to its original location) when typing: