-->

我怎么能得到当前的UITextField的属性名称的用户是一个字符串?(How could I ge

2019-10-17 09:05发布

我使用下面的方法:

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

之前,为了查找当前文本字段我在,我能写的东西是这样的:

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

是否有办法抢我的名字textField作为一个字符串? 我不要求采取什么样的用户在已键入textField ,我希望能够得到公正的,如果属性名称。 我需要它,然后与其他一些字符串拼接它。 我正在做一个动态的方法调用。

Answer 1:

主要分配唯一的代码给每个TextField的(例如1,2,3 ......)避免0包含textField标签

-(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
}

进一步..

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

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

}


Answer 2:

UITextField都不具备的“名字”。 你可以给你的文本字段tag和使用。

另外,还要注意(pointer == pointer) ,如果你引用的是相同的对象 ,并不等同值仅返回true。

下面是如何使用该标签:如果您创建编程文本字段在Interface Builder中,给每一文本字段标签,或者设置textField.tag = someInt; 我通常使用宏来使得代码更易读:

#define kNameTextField 2
#define kAddressTextField 3

...

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

有很多这样的领域中,我更喜欢枚举:

typedef enum {
  kNameTextField = 2, 
  kAddressTextField, 
  kPhoneTextField // etc
} Fields;


Answer 3:

您可以使用此代码得到的属性(在你的情况textField属性)名称:

-(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;
} 

记得导入:

#import <objc/runtime.h>

只要致电:

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

资源



文章来源: How could I get the property name of the current UITextField a user is in as a string?