如何在 iOS 5 中添加多个 UITextfield? [英] How to add multiple UITextfield in iOS 5?
问题描述
如何创建多个 UITextField 并将其添加到我的控制器?
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]
但是我需要为每个 UITextField 都这样做吗?
But do I need to do that for each UITextField?
模板 UI 控件的最佳方法是什么?
Whats the best approach to template UI Controls?
推荐答案
把它放在一个循环中,偏移每个文本字段的 Y 位置并标记每个文本字段:
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
}
然后在委托方法中根据调用每个委托方法的 textField 的标签执行操作.例如,当用户点击返回键时切换到下一个文本视图:
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];
}
请记住,在 Objective-C 中向 nil 发送消息不会崩溃,因此当用户点击最后一个文本字段中的返回键时,它会完全没问题 UITextField *nextTextField = [self.view viewWithTag:textField.tag+ 1];
将返回 nil,并且在 nil 上调用 becomeFirstResponder
将什么也不做.但是你可以检查 nextTextField 是否为 nil ,然后做其他事情,无论你喜欢什么.
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.
这篇关于如何在 iOS 5 中添加多个 UITextfield?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!