我正在开发一个需要根据从Web服务收到的json动态生成UITextField的应用程序。实际上它是一个视图结构。它包含文本字段对象的坐标及其详细信息。我正在使用预定义数量的文本字段生成结构。
for (int i=0; i<[textFieldsArray count];i++) {
NSDictionary *textFieldDict = [textFieldsArray objectAtIndex:i];
switch (i+1) {
case 1:
textField1 = [[UITextField alloc]init];
textField1.tag = i+1;
textField1.text = [textFieldDict valueForKey:@"text"];
textField1.frame = CGRectMake(posx,posy,textWidth,textHeight);
[textField1 addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventTouchDown];
[self.imageView addSubview:textField1];
break;
case 2:
textField2 = [[UITextField alloc]init];
textField2.tag = i+1;
textField2.text = [textFieldDict valueForKey:@"text"];
textField2.frame = CGRectMake(posx,posy,textWidth,textHeight);
[self.imageView addSubview:textField2];
[textField2 addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventTouchDown];
break;
case 3:
textField3 = [[UITextField alloc]init];
textField3.tag = i+1;
textField3.text = [textFieldDict valueForKey:@"text"];
textField3.frame = CGRectMake(posx,posy,textWidth,textHeight);
[self.imageView addSubview:textField3];
[textField3 addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventTouchDown];
break;
default:
break;
}
}
我想将其扩展为无限的文本字段。有没有办法动态创建文本字段。
答案 0 :(得分:3)
你必须像这样创建:
for (int i=0; i<[textFieldsArray count];i++) {
NSDictionary *textFieldDict = [textFieldsArray objectAtIndex:i];
UITextField *textField = [[UITextField alloc]init];
textField.tag = i+1;
textField.text = [textFieldDict valueForKey:@"text"];
textField.frame = CGRectMake(posx,posy,textWidth,textHeight);
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventTouchDown];
[self.imageView addSubview:textField];
}
您可以使用以下代码获取任何文本字段:
UITextField *textField = (UITextField *)[self.imageView viewWithTag:1];