iOS之UITextField切换焦点

如图:页面中有两个密码输入框,一个UIButton,初始化时UIButton不可点击,当两个输入框内容均不为空,按钮可以点击;若任意一个为空,则不可点击。



很多时候,我们都会重写UITextField的代理方法,通过输入框内容变化来动态决定UIButton是否可用。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    ....处理你的Button.......
    
    return YES;
    
}

但经过测试发现:两个UITextField输入内容后,在键盘不关闭的情况下把光标切换至另外一个输入框,一旦用退格键删除最后一个字符或中间某个字符,整个UITextfield的内容被清空了,这时Button不会起任何变化。

解决方法:

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textFieldTextDidChange:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:nil
     ];

#pragma mark - UITextField Delegate
- (void)textFieldTextDidChange:(NSNotification *)notification
{
    UITextField *tf = (UITextField *)[self.view viewWithTag:TextField_Tag_Password];
    UITextField *tf2 = (UITextField *)[self.view viewWithTag:TextField_Tag_Password2];
    UIButton *btn = (UIButton *)[self.view viewWithTag:Button_Tag_Confirm];
    
    if ([Utils isEmpty:tf.text] || [Utils isEmpty:tf2.text]) {
        btn.backgroundColor = DisableButtonColor;
        btn.enabled = NO;
    } else {
        btn.backgroundColor = ThemeColor;
        btn.enabled = YES;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值