Skip to content

Instantly share code, notes, and snippets.

@michaelevensen
Created September 6, 2018 12:35
Show Gist options
  • Save michaelevensen/2a7c168af2e429129368c74540b404dc to your computer and use it in GitHub Desktop.
Save michaelevensen/2a7c168af2e429129368c74540b404dc to your computer and use it in GitHub Desktop.
Binds the specified UIView so that the UIVIew slides up and down based on the keyboards visibility. Do a `self.view.bindToKeyboard()` in `viewDidLoad` and you should be good.
extension UIView {
func bindToKeyboard() {
NotificationCenter.default.addObserver(self, selector: #selector(UIView.keyboardWillChange(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
@objc func keyboardWillChange(_ notification: NSNotification) {
let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
let curFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let targetFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let deltaY = targetFrame.origin.y - curFrame.origin.y
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
self.frame.origin.y += deltaY
},completion: {(true) in
self.layoutIfNeeded()
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment