Skip to content

Instantly share code, notes, and snippets.

@alexito4
Created June 16, 2016 14:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexito4/3b6585209503c98d5fa21c25372ff03c to your computer and use it in GitHub Desktop.
Save alexito4/3b6585209503c98d5fa21c25372ff03c to your computer and use it in GitHub Desktop.
import UIKit
public protocol KeyboardAvoidance: class {
var scrollView: UIScrollView { get }
}
private var willShowTokenKey = "willShowTokenKey"
private var willHideTokenKey = "willHideTokenKey"
public extension KeyboardAvoidance where Self: UIViewController {
var willShowToken: NSObjectProtocol? {
get {
return objc_getAssociatedObject(self, &willShowTokenKey) as? NSObjectProtocol
}
set(newValue) {
objc_setAssociatedObject(self, &willShowTokenKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
var willHideToken: NSObjectProtocol? {
get {
return objc_getAssociatedObject(self, &willHideTokenKey) as? NSObjectProtocol
}
set(newValue) {
objc_setAssociatedObject(self, &willHideTokenKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
func startKeyboardAvoidance() {
willShowToken = NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillShowNotification, object: nil, queue: NSOperationQueue.mainQueue()) { [weak self] notif in
self?.scrollView.keyboardWillShow(notif)
}
willHideToken = NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillHideNotification, object: nil, queue: NSOperationQueue.mainQueue()) { [weak self] notif in
self?.scrollView.keyboardWillHide(notif)
}
}
func stopKeyboardAvoidance() {
_ = willShowToken.map(NSNotificationCenter.defaultCenter().removeObserver)
_ = willHideToken.map(NSNotificationCenter.defaultCenter().removeObserver)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment