Created
September 6, 2018 12:35
-
-
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.
This file contains hidden or 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 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