How to add multiple UITextfield in iOS 5?

社会主义新天地 提交于 2019-12-25 19:37:00

问题


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?


回答1:


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.




回答2:


You can use interface builder to create a view (bigger than the size that the screen fits) and programmatically add it to a scrollView. This is in my opinion the best approach.



来源:https://stackoverflow.com/questions/9247509/how-to-add-multiple-uitextfield-in-ios-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!