Skip to content

Instantly share code, notes, and snippets.

@rpassis
Last active November 3, 2016 22:23
Show Gist options
  • Save rpassis/5b6321b43111bba6792e2df8c7ba9071 to your computer and use it in GitHub Desktop.
Save rpassis/5b6321b43111bba6792e2df8c7ba9071 to your computer and use it in GitHub Desktop.
Protocol for observing keyboardWillShow & keyboardWillHide notifications
import UIKit
protocol KeyboardObservable {
var bottomSpaceToMainViewConstraint: NSLayoutConstraint! { get }
func subscribeToKeyboardNotifications()
}
extension KeyboardObservable where Self: UIViewController {
func subscribeToKeyboardNotifications() {
NotificationCenter.default.addObserver(forName: .UIKeyboardWillShow, object: nil, queue: nil) { [weak self] (notification) in
if let userInfo = notification.userInfo, let keyboardFrame = self?.getKeyboardRect(forKey: UIKeyboardFrameEndUserInfoKey, withUserInfo: userInfo), let values = self?.getDurationAndCurve(fromNotificationUserInfo: userInfo) {
UIView.animate(withDuration: values.duration, delay: 0, options: UIViewAnimationOptions(rawValue: values.curve), animations: {
self?.bottomSpaceToMainViewConstraint.constant = keyboardFrame.size.height
self?.view.layoutIfNeeded()
})
}
}
NotificationCenter.default.addObserver(forName: .UIKeyboardWillHide, object: nil, queue: nil) { [weak self] (notification) in
if let userInfo = notification.userInfo, let values = self?.getDurationAndCurve(fromNotificationUserInfo: userInfo) {
UIView.animate(withDuration: values.duration, delay: 0, options: UIViewAnimationOptions(rawValue: values.curve), animations: {
self?.bottomSpaceToMainViewConstraint.constant = 0
self?.view.layoutIfNeeded()
})
}
}
}
func getKeyboardRect(forKey key: String, withUserInfo userInfo: [AnyHashable: Any]) -> CGRect? {
return (userInfo[key] as? NSValue)?.cgRectValue
}
func getDurationAndCurve(fromNotificationUserInfo userInfo: [AnyHashable: Any]) -> (duration: TimeInterval, curve: UInt)? {
guard let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval, let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? UInt else {
return nil
}
return (duration, curve)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment