1

I am using the following method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string

Before, in order to find the current text field I was in, I was able to write something like this:

if (textField == self.textPlaceID)
{
    //Do something
}

Is there a way to grab the name of my textField as a string? I am not asking to take what the user has typed in that textField, I'd like to be able to just get the property name of if. I need it to then concatenate it with some other strings. I am working on making a dynamic method call.

rmaddy
  • 314,917
  • 42
  • 532
  • 579

3 Answers3

4

UITextFields do not have "names". You can give your text field a tag and use that.

Also, note that (pointer == pointer) will only return true if you are referencing the same objects, not equivalent values.

Here is how to use the tag: in Interface Builder, give each text field a tag, or if you create your text fields programmatically, set textField.tag = someInt; I usually use macros to make the code more readable:

#define kNameTextField 2
#define kAddressTextField 3

...

if (textField.tag == kNameTextField) ...

With lots of fields like that, I prefer enums:

typedef enum {
  kNameTextField = 2, 
  kAddressTextField, 
  kPhoneTextField // etc
} Fields;
Mundi
  • 79,884
  • 17
  • 117
  • 140
1

You can get name of property (in your case textField property) using this code:

-(NSString *)propertyName:(id)property {  
    unsigned int numIvars = 0;
    NSString *key=nil;
    Ivar * ivars = class_copyIvarList([self class], &numIvars);
    for(int i = 0; i < numIvars; i++) {
    Ivar thisIvar = ivars[i];
    if ((object_getIvar(self, thisIvar) == property)) {
        key = [NSString stringWithUTF8String:ivar_getName(thisIvar)];
        break;
    }
} 
    free(ivars);
    return key;
} 

Remember to import:

#import <objc/runtime.h>

Just call:

NSLog(@"name = %@", [self propertyName:self.textField]);

source

Community
  • 1
  • 1
edzio27
  • 4,126
  • 7
  • 33
  • 48
0

Primarily assign unique tags to each of the textFields (eg 1,2,3.....) avoid 0 for a textField tag

-(void)viewDidLoad{
NSDictionary *dictionary ; //declare it in .h interface

dictionary =  [NSDictionary dictionaryWithObjectsAndKeys:@"textPlaceID",[NSNumber numberWithInt:1], @"textPlaceID2",[NSNumber numberWithInt:2],nil]; // add textField as object and tag as keys
}

further..

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string{

NSString *textFieldPropertyName = [dictionary objectForKey:[NSNumber numberWithInt:textField.tag]];

}
AppleDelegate
  • 4,269
  • 1
  • 20
  • 27