Skip to content

Instantly share code, notes, and snippets.

@bhrott
Created May 1, 2018 16:44
Show Gist options
  • Save bhrott/7a89ea0cb435c924cf289f58c37e79cc to your computer and use it in GitHub Desktop.
Save bhrott/7a89ea0cb435c924cf289f58c37e79cc to your computer and use it in GitHub Desktop.
iOS KeyboardBindView extension
import Foundation
import UIKit
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
}) { (true) in
self.layoutIfNeeded()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment