Created
May 22, 2015 11:13
-
-
Save kirsteins/a3a1df5971990a4cd69e to your computer and use it in GitHub Desktop.
Associated object
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 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