是否可以使用setValue为for循环中的多个对象设置UITextField的文本字段:forKey:?如果我应该以某种方式在属性名称中指定“text”,或者如果我遗漏了其他内容,我会感到有点困惑?
// INTERFACE
@property(nonatomic, retain) IBOutlet UITextField *textFieldBit_01;
@property(nonatomic, retain) IBOutlet UITextField *textFieldBit_02;
@property(nonatomic, retain) IBOutlet UITextField *textFieldBit_03;
@property(nonatomic, retain) IBOutlet UITextField *textFieldBit_04;
@property(nonatomic, retain) IBOutlet UITextField *textFieldBit_05;
// IMPLEMENT
@synthesize textFieldBit_01;
@synthesize textFieldBit_02;
@synthesize textFieldBit_03;
@synthesize textFieldBit_04;
@synthesize textFieldBit_05;
for(unsigned int counter=1; counter<=5; counter++) {
NSString *propertyName = [[NSString alloc] initWithFormat:@"textFieldBit_%02d.text",counter];
NSString *propertyValue = [[NSString alloc] initWithFormat:@"%d", counter];
[self setValue:propertyValue forKey:propertyName];
[propertyName release];
[propertyValue release];
}
也许我应该尝试澄清一下我的问题:我基本上试图在每次循环循环时在5个UITextField之一上设置文本。我可以使用“if”或“switch”但看起来有点像矫枉过正。我想也许是setValue:forKey:让我通过在每次迭代中构建一个唯一的密钥并使用一个调用来实现它。
if(counter == 1) [textFieldBit_01 setText:@"%02d", 1];
if(counter == 2) [textFieldBit_02 setText:@"%02d", 2];
if(counter == 3) [textFieldBit_03 setText:@"%02d", 3];
if(counter == 4) [textFieldBit_04 setText:@"%02d", 4];
if(counter == 5) [textFieldBit_05 setText:@"%02d", 5];
NSString *propertyName = [[NSString alloc] initWithFormat:@"labelBit_%02d.text",counter];
NSString *propertyValue = [[NSString alloc] initWithFormat:@"%d", geoTag];
[self setValue:propertyValue forKeyPath:propertyName];
感谢您的回答,我现在明白我哪里出错,我正在使用的是setValue:forKey:当我需要访问“labelBit_01.text”的情况时,我本应该使用setValue:forKeyPath:
加里
答案 0 :(得分:2)
尝试
[self setValue:propertyValue forKeyPath:[propertyName stringByAppendingString:@".text"]];
这最终给你的是:
self.textFieldBit_01.text = @"01";