Emil
Emil

Reputation: 47

Adding multiple text fields with the same code

I want to be able to add between 1 and 20 text fields to my view with the same code.

My idea is to use a for loop and every time add a text field so the first time it loops it adds "textField1" and the second time it adds "textField2" etc.

I'm not sure how I would go about coding this so I'm looking for your help.

Upvotes: 0

Views: 482

Answers (3)

Magyar Miklós
Magyar Miklós

Reputation: 4272

NSMutableArray* tfArray = [[NSMutableArray alloc]init];


for (int i = 0; i < 20; i++)
{
    UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];

    [self.view addSubview:textField];
    [tfArray addObject:textField];

}

if you want to reference a field:

the 6th textfield is for example: (UITextField*)tfArray[5];

Upvotes: 1

kshitij godara
kshitij godara

Reputation: 1523

Try this code

for 20 textfields you need to take them in UIScrollView .. you can do like this --

UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,0,320,460)];

[scrollView setDelegate:self];

//initialize a textfield array;

NSMutableArray *textFieldArray = [[NSMutableArray alloc]init];

//x, y for first textfield in UIScrollView

float x = 20;

float y = 20;

For(int i=1;i<21;i++)
{
   UITextfield *textField = [[UITextfield alloc]initWithFrame:CGRectMake(x,y,200,30)];
   textfield.tag = i;
   [textField setDelegate:self];

   //Add Textfield to array just for futureRefrence

   [textFieldArray addObject:textField];

   //Add textfield in UIScrollView

   [scrollView addSubview:textField];

   //Now iterate Y , So they won't over each other

   y = y+50;

}

//Now set ScrollView ContentSize 

[scrollView setContentSize:CGSizeMake:(320,20*y)];

//Now Finally Add ScrollView in UIView

[self.view addSubView:scrollView];

Also remember declare there delegate in .h file . and you can access these textfield by the array you put them in ,For Example

If you want a value from textfield three , you can do like this

UITextfield *textfield = (UITextfield *)[textFieldArray objectAtIndex:2];
NSLog(@"text of textField 3 is -- %@",textfield.text);

Upvotes: 1

wattson12
wattson12

Reputation: 11174

for (int i = 0; i < 20; i++)
{
    UITextField *textField = //setup field
    textField.tag = i;
    [self.view addSubview:textField];
}

then when you want to reference a field later

UITextField *textField6 = [self.view viewWithTag:6];
UITextField *textField18 = [self.view viewWithTag:18];
etc

Upvotes: 1

Related Questions