Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.