我根据UITextField
的计数在视图中创建NSArray
。
我想知道如何根据UITextField
中NSArray
的标记访问文本值。
所以在我将以下UITextField
添加到我的视图后,我将如何编写代码来分别检索myTextfield0,myTextfield1和myTextfield2的.text值?
示例:
NSString *textFeildTextString = [NSString stringWithFormat:@"%@",myTextfield1.text];
实际代码:
self.textFieldArray = [NSArray arrayWithObjects:@"one", @"two", @"three",nil];
NSMutableDictionary *myDict = [NSMutableDictionary dictionary];
for (int i=0; i<[self.textFieldArray count]; i++) {
UIView *spacerView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
UITextField *myTextField = [[UITextField alloc]initWithFrame:CGRectMake(20, 60*i+150, 280, 45)];
myTextField.borderStyle = UITextBorderStyleNone;
myTextField.font = [UIFont systemFontOfSize:14];
myTextField.returnKeyType = UIReturnKeyDefault;
myTextField.placeholder = NSLocalizedString(@"Answer", nil);
myTextField.inputAccessoryView = [super createInputToolbar];
myTextField.background = [UIImage imageNamed:@"TextFieldBg"];
myTextField.textColor = [UIColor appTextColorGrey];
[myTextField setLeftView: spacerView1];
myTextField.leftViewMode = UITextFieldViewModeAlways;
myTextField.delegate = self;
myTextField.tag = 200+i;
[myDict setObject:myTextField forKey:[NSString stringWithFormat:@"myTextfield%d", i]];
[self.view addSubview:myTextField];
}
NSLog(@"Dict: %@",myDict);
我的UITexfields的NSlog
2014-10-31 11:58:32.715 [51992:13536821] Dict: {
myTextfield0 = "<UITextField: 0x7faea14f8430; frame = (20 150; 280 45); text = ''; clipsToBounds = YES; opaque = NO; tag = 200; layer = <CALayer: 0x7faea14f82d0>>";
myTextfield1 = "<UITextField: 0x7faea14fae70; frame = (20 210; 280 45); text = ''; clipsToBounds = YES; opaque = NO; tag = 201; layer = <CALayer: 0x7faea14faca0>>";
myTextfield2 = "<UITextField: 0x7faea16dce30; frame = (20 270; 280 45); text = ''; clipsToBounds = YES; opaque = NO; tag = 202; layer = <CALayer: 0x7faea16d19c0>>";
}
答案 0 :(得分:2)
for (int i=0; i<[self.textFieldArray count]; i++) {
UITextField *txt = (UITextField *)[myDict objectForKey:[NSString stringWithFormat:@"myTextfield%d", i]];
NSLog(@"Text %@",txt.text);
}
答案 1 :(得分:0)
您可以通过标签访问它们:
UITextField *textField= (UITextField *)[self.view viewWithTag:200]; // Your first text field (201 your second etc..)
NSString *text = textField.text;
或者直接通过字典访问它们,因为您已经知道每个字典的关键字:
UITextField *textField = (UITextField *)[myDict objectForKey:@"myTextField0"];
请注意,为了让字典留在你的类中声明一个强属性成员并将其分配给创建的本地字典(否则它将被ARC丢失)所以在方法结束时你会有类似的东西:
self.myDict = myDict;