How to set the current value of UITextField
to a property(through a custom setter) declared in category which extends UITextField
class when firing editingDidBegin
control event of UITextField
?
Asked
Active
Viewed 107 times
0

Rakesha Shastri
- 11,053
- 3
- 37
- 50

PSkyMax
- 1
- 1
-
Explain your question briefly. – Mathi Arasan Aug 13 '18 at 09:06
-
I want to get the current value of UITextField to a variable when "UIControlEventEditingDidBegin" control event fires. I also want to add this behavour to all of my UITextField objects to check whether textfield value is edited or not. So I created a category which extends UITextField class and add a public property to store the value and now I want to set the textfield's value to this property when "UIControlEventEditingDidBegin" UITextcField's control event fires . Thanks ... – PSkyMax Aug 13 '18 at 09:49
1 Answers
1
You should be able to do this using a category by taking advantage of Associative References.
Using associative references, you can add storage to an object without modifying the class declaration.
Here's an example that will get you going in the right direction:
.h file:
@interface UITextField (StoredProperty)
@property (nonatomic, strong) NSString *testString;
@end
.m file:
#import <objc/runtime.h>
static void *MyStoredPropertyKey = &MyStoredPropertyKey;
@implementation UITextField (StoredProperty)
- (NSString *)testString {
return objc_getAssociatedObject(self, MyStoredPropertyKey);
}
- (void)setTestString:(NSString *)testString {
objc_setAssociatedObject(self, MyStoredPropertyKey, testString, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
Example use:
NSObject *obj = [NSObject new];
obj.testString = @"This is my test string";
NSLog(@"%@", obj.testString);

tww0003
- 801
- 9
- 18
-
Thanks @ tww0003 for your answer. I also followed associative references. But how to set the UITextField's value to "testString" property when "UIControlEventEditingDidBegin" control event fire? – PSkyMax Aug 14 '18 at 03:55
-
@PSkyMax You could create another category, but this time for UITextFieldDelegate and set it in the `textFieldDidBeginEditing:` method. Hope this helped, and if it did don't forget to mark the answer as accepted! Here's the relevant documentation: https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619590-textfielddidbeginediting?language=objc – tww0003 Aug 14 '18 at 14:22