Reputation: 3349
I am working on a app that need to generate UITextFields dynamically according to the json that recieved from a web service. Actually it is a view structure. It contains cordinates of the text field objects and their details. I am generating the structure using pre defined number of text fields.
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;
}
}
I wanted to expand this into infinite text fields. Is there a way to create textfields dynamically.
Upvotes: 0
Views: 858
Reputation: 671
You have to create like this:
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];
}
You can get any text field using code below:
UITextField *textField = (UITextField *)[self.imageView viewWithTag:1];
Upvotes: 3