IOS之UITextField与键盘

场景

登录界面,需要输入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];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值