3

I want to create textfields based on user input. Let's say 5 textfield are needed

for (int x = 0; x < self.howMany; x++) 
{
    NSLog(@"%i", x_position);
    self.textFieldRounded = [[UITextField alloc] initWithFrame:CGRectMake(10, x_position, 300, 25)];
    self.textFieldRounded.borderStyle = UITextBorderStyleRoundedRect;
    self.textFieldRounded.textColor = [UIColor blackColor]; //text color
    self.textFieldRounded.font = [UIFont systemFontOfSize:17.0];  //font size

    [self.view addSubview:self.textFieldRounded];
    x_position += 30;
}

So far, so good. That code create five textfields. The problem is that these textfields are not "unique". Each of these textfield can contain different information. What to do so that I can gather information of each of these fields ?

Profo
  • 153
  • 2
  • 2
  • 11

4 Answers4

4

Add a tag to them.

int i = 1;
for (int x = 0; x < self.howMany; x++) 
{
    NSLog(@"%i", x_position);
    self.textFieldRounded = [[UITextField alloc] initWithFrame:CGRectMake(10, x_position, 300, 25)];
 textFieldRounded.tag = i++;
 ...

And then, when you need to find textfield 3 for example, do:

UITextField *textField = (UITextField *)[self.view viewWithTag:3];
vakio
  • 3,134
  • 1
  • 22
  • 46
1

You could set a tag for each text field.

self.textFieldRounded.tag = x;

Then you can use the tag to identify your text fields. You can iterate through self.view to find all subviews (text fields) using this technique.

Community
  • 1
  • 1
pojo
  • 5,892
  • 9
  • 35
  • 47
  • Only problem with setting the tag to x is the first tag will be 0 and all views have 0 by default so the first textfield cannot be located by tag. – vakio Feb 08 '12 at 10:24
0

I think you should take different TextField for each information so that everything should be clear and if you still want to use one text field then you can set the tag for each info.

Mudit Bajpai
  • 3,010
  • 19
  • 34
0

You could add a reference to each TextField in an NSMutableArray and then iterate through the array using something like

for (UITextField *tmp in myArray) {
//do stuff with the textfield
}
Amit Shah
  • 4,176
  • 2
  • 22
  • 26