Skip to content

Instantly share code, notes, and snippets.

@kirsteins
Created May 22, 2015 11:13
Show Gist options
  • Save kirsteins/a3a1df5971990a4cd69e to your computer and use it in GitHub Desktop.
Save kirsteins/a3a1df5971990a4cd69e to your computer and use it in GitHub Desktop.
Associated object
import ObjectiveC
import UIKit
var associatedObjectHandle: UInt8 = 0
class TextDidChangeHandler: NSObject {
unowned let textField: UITextField
let handler: (textField: UITextField) -> Void
init(textField: UITextField, handler: (textField: UITextField) -> Void) {
self.handler = handler
self.textField = textField
super.init()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange:", name: UITextFieldTextDidChangeNotification, object: self.textField)
}
func textDidChange(notification: NSNotification) {
handler(textField: self.textField)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
extension UITextField {
public var textDidChange: ((textField: UITextField) -> Void)? {
get {
let object = objc_getAssociatedObject(self, &associatedObjectHandle) as? TextDidChangeHandler
return object?.handler
}
set {
if let handler = newValue {
let object = TextDidChangeHandler(textField: self, handler: handler)
objc_setAssociatedObject(self, &associatedObjectHandle, object, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
} else {
objc_removeAssociatedObjects(self)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment