Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

uikit - How to add multiple UITextfield in iOS 5?

How do I create and add multiple UITextField to my controller?

I can create one, like this:

UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(5,5,100,25)];
tf.borderStyle = UITextBorderStyleRoundedRect;
[tf setReturnKeyType:UIReturnKeyDefault];
[tf setEnablesReturnKeyAutomatically:YES];
[tf setDelegate:self];
[self.view addSubview:tf]

But do I need to do that for each UITextField?

Whats the best approach to template UI Controls?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Put it in a loop, offset each text field's Y position and tag each text field:

for (int i = ; i < numberOfTextFieldsNeeded; i++) {
    UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(5, 5 + 35 * i ,100,25)]; // 10 px padding between each view
    tf.tag = i + 1; // tag it for future reference (+1 because tag is 0 by default which might create problems)
    tf.borderStyle = UITextBorderStyleRoundedRect;
    [tf setReturnKeyType:UIReturnKeyDefault];
    [tf setEnablesReturnKeyAutomatically:YES];
    [tf setDelegate:self];
    [self.view addSubview:tf]
    // don't forget to do [tf release]; if not using ARC
}

Then in delegate methods perform actions based on tag of the textField that called each delegate method. For example to switch to next text view when user taps return key:

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
    UITextField *nextTextField = [self.view viewWithTag:textField.tag + 1];
    [nextTextField becomeFirstResponder];
}

Keep in mind that sending messages to nil in Objective-C will not crash so it will be perfectly fine when user taps return key in last text field as UITextField *nextTextField = [self.view viewWithTag:textField.tag + 1]; will return nil, and calling becomeFirstResponder on nil will do nothing. But you can check if nextTextField is nil and do something else then, whatever you like.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...