How to create dynamic UITextField with different object name?

ios

Solution

There is absolutely not a reason to create text fields with a different (unique name). I'm pretty sure the reason you want the unique name, is so you can access them later in your code and edit their values, but here comes the trick: Use unique tag numbers.

Here is an example:

for (int i=0; i<4; i++) {
    UITextField *myTextfield = [[UITextField alloc] initWithFrame:CGRectZero];
    myTextField.tag = 200+i;
    [self.view addSubview:myTextField];
}

Now we have created 4 text fields, which have tags 200, 201, 202 and 203

Later in code when we want to reference the second text field for example, all we have to do is this:

UITextField *myTextField = (UITextField *)[self.view viewWithTag:201];

now we have the control and we can get or set anything...

As a precaution I would suggest you check you actually got the UI element, by using:

if (!myTextField)
   return;

Problem

I want to create dynamic UITextField with different object name.I have shown the code below for creating textfield dynamically. How can i create each textfield with different object name ? ``` for (int x=0; x < 4 ; x++) { CGRect txtFldFrame; if (x==0) txtFldFrame=CGRectMake(385, 620, 278, 45); else txtFldFrame=CGRectMake(385, txtFldFrame.origin.y+60, 278, 45); [self createTxtImg:txtImgFrame createTextfield:txtFldFrame]; } ``` In the createTextfield:(CGRect )txtfldframe { ``` UITextField *txtFld1=[[UITextField alloc]init]; txtFld1.frame=txtfldframe; [txtFld1 setTag:textChk]; txtFld1.borderStyle = UITextBorderStyleNone; txtFld1.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; txtFld1.textAlignment=UITextAlignmentLeft; txtFld1.textColor=[UIColor colorWithRed:17/255.0 green:61/255.0 blue:83/255.0 alpha:1]; txtFld1.font = [UIFont systemFontOfSize:22]; txtFld1.backgroundColor = [UIColor clearColor]; txtFld1.autocorrectionType = UITextAutocorrectionTypeNo; txtFld1.returnKeyType = UIReturnKeyDone; txtFld1.clearButtonMode = UITextFieldViewModeWhileEditing; txtFld1.autocapitalizationType=UITextAutocapitalizationTypeNone; txtFld1.delegate = self; [subScrollView addSubview:txtFld1]; ``` }

Original source