Skip to content

Instantly share code, notes, and snippets.

@emajcher
Last active June 21, 2016 14:37
Show Gist options
  • Save emajcher/9534f151ba80b8ab0199a16565095734 to your computer and use it in GitHub Desktop.
Save emajcher/9534f151ba80b8ab0199a16565095734 to your computer and use it in GitHub Desktop.
//
// KeyboardHandler.swift
//
// Helper protocol and extension to consolidate keyboard notification handling for
// UIViewControllers.
//
// Created by Edward Majcher on 6/21/16.
//
import UIKit
@objc
protocol KeyboardNotificationHandler {
func keyboardWillShow(note: NSNotification)
func keyboardWillHide(note: NSNotification)
}
extension KeyboardNotificationHandler where Self: UIViewController {
func registerForKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Self.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Self.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
func unregsiterForKeyboardNotifications() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardValues(fromNote note:NSNotification) -> (begin: CGRect, end: CGRect, duration: NSTimeInterval, curve: UIViewAnimationCurve)? {
guard let userInfo = note.userInfo,
begin = userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue,
end = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue,
duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSValue,
curve = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSValue else {
return nil
}
var animationDuration: NSTimeInterval = 0
var animationCurve: UIViewAnimationCurve = .EaseIn
duration.getValue(&animationDuration)
curve.getValue(&animationCurve)
return (begin.CGRectValue(), end.CGRectValue(), animationDuration, animationCurve)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment