场景
登录界面,需要输入11位手机号码和密码。
解决
为更好的体验,当用户输入了11位手机号的时候,自动跳到下一个输入框。
UITextField有代理方法,但是没有在输入框内容改变之后的回调方法。
这时候,我们会用
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
方法来实现输入11位手机号的时候,跳到下一个输入框。
假设如下这样
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == _phoneTextField) {
NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
NSLog(@"content %@",toBeString);
if (toBeString.length == 11) {
[_phoneTextField resignFirstResponder];
[_passwordField becomeFirstResponder];
}
}
return YES;
}
会发现,手机号输入了10位,输入第11位的时候,键盘焦点立即跑到下一个输入框,致使手机号框10位,密码框1位。
这时候,有的方案是加个延迟,将变化焦点的代码延迟执行.
代理方法中没有输入框变化后的方法,但是却提供了通知UITextFieldTextDidChangeNotification,注册这个通知,可获得输入框变化后的情况。
- (void)addTextFieldObserver
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTextFieldTextDidChange:) name:UITextFieldTextDidChangeNotification object:_phoneTextField];
}
- (void)onTextFieldTextDidChange:(NSNotification *) notification
{
id object = notification.object;
if (object == _phoneTextField) {
if (_phoneTextField.text.length == 11) {
[_phoneTextField resignFirstResponder];
[_passwordField becomeFirstResponder];
}
}
}
使用这个方法,就不必去为焦点变化加延迟了,输入11个后就跳到下面去了。
另外
一般,还需要点击空白背景,使得键盘隐藏。
有的是将UIView改为UIControl,使得它能够响应事件。
觉得还是为View增加手势比较合适,加个UITapGestureRecognizer。
//增加隐藏键盘的手势
- (void)addHiddenKeyBoardTagGesture
{
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenKeyBoard)];
[self.view addGestureRecognizer:tapGesture];
}
- (void)hiddenKeyBoard
{
[self.view endEditing:YES];
}