问题描述
我已经搜索并看到很多关于textFieldShouldReturn方法的答案。其中一半是过时的,有些工作在不同的情况下,一些没有彻底解释。我不知道什么是最好的方式来做这个任务,它的工作,但我认为可能会有一个更简单的方法。
I have searched and seen a lot of answers about textFieldShouldReturn method. Half of them are outdated, some work in different cases, some are not explained thoroughly. I am not sure what is the most optimal way to do this task, it works but I think there might be an easier way to do it.
我的代码到目前为止:
在头文件中:
@interface ClassName : SomeUIViewController <UITextFieldDelegate>
在实现文件中:
@interface ClassName()
@property (weak, nonatomic) IBOutlet UITextField *firstOne;
@property (weak, nonatomic) IBOutlet UITextField *secondOne;
@property (weak, nonatomic) IBOutlet UITextField *thirdOne;
@property (weak, nonatomic) IBOutlet UITextField *fourthOne;
@property (weak, nonatomic) IBOutlet UITextField *fifthOne;
@end
-(void)viewDidLoad{
self.firstOne.delegate = self;
self.secondOne.delegate = self;
self.thirdOne.delegate = self;
self.fourthOne.delegate = self;
self.fifthOne.delegate = self;
}
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
if (textField == self.firstOne) {
[textField resignFirstResponder];
[self.secondOne becomeFirstResponder];
} else if (textField == self.secondOne) {
[textField resignFirstResponder];
[self.thirdOne becomeFirstResponder];
} else if (textField == self.thirdOne) {
[textField resignFirstResponder];
[self.fourthOne becomeFirstResponder];
} else if (textField == self.fourthOne) {
[textField resignFirstResponder];
[self.fifthOne becomeFirstResponder];
} else if (textField == self.fifthOne) {
[textField resignFirstResponder];
}
return NO;
}
这是正确的还是有更好的方法来完成这项工作? p>
So is this correct or are there better ways to do this task?
推荐答案
一般来说,你的代码很好。
In general your code is fine.
如果你使用IB (Interface Builder)可以在代码中设置代理,而不是代码。
If you are using IB (Interface Builder) you can set the delegate there instead of in code.
示例:控制从UITextField拖动到ViewController并选择委托。
Example: control drag from the UITextField to the ViewController and select "delegate".
resignFirstResponder可以考虑到ibe发生
重构代码:
The resignFirstResponder could be factored to ibe occurrence
Refactored code:
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
[textField resignFirstResponder];
if (textField == self.firstOne) {
[self.secondOne becomeFirstResponder];
} else if (textField == self.secondOne) {
[self.thirdOne becomeFirstResponder];
} else if (textField == self.thirdOne) {
[self.fourthOne becomeFirstResponder];
} else if (textField == self.fourthOne) {
[self.fifthOne becomeFirstResponder];
}
return NO;
}
这篇关于文本字段应该返回,这对ios7是正确的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!