-
-
Save alexito4/3b6585209503c98d5fa21c25372ff03c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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