2

I create programmatically 12 textfields using one method and I add a tag to each. Below is the method that creates the textfields, this is called 12 times to create each of the textfields. This works.

textField = [[UITextField alloc] initWithFrame:CGRectMake(x, y, w, h)];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.font = [UIFont systemFontOfSize:15];
textField.placeholder = name;
[textField setTag:tag];
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[self.view addSubview:textField];

My question is how do I set the text in each textfield or how do I access it using the tags.

I tried:

[textField.2 setText: [NSString stringWithFormat : @"HEY"]];

and that does not work.

1
  • 1
    Don't use stringWithFormat: this way, it's superfluous. @"HEY" is already a string.
    – rdelmar
    Jan 30, 2013 at 0:18

1 Answer 1

3
[(UITextField *)[self.view viewWithTag:2] setText:@"foobar"];

It's often a better idea to create an NSArray property that contains the text fields though.

2
  • 2
    If you do it this way, just make sure you don't use 0 as one of your tags, since that's the default, and other views in the hierarchy will have a 0 tag. But I agree with omz, putting them in an array is probably better.
    – rdelmar
    Jan 30, 2013 at 0:19
  • This does not work, as I get "No visible @interface for UIView declares selector setText
    – Tori
    Jan 30, 2013 at 0:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.