如何实时检查文本字段输入? [英] How to check text field input at real time?

查看:153
本文介绍了如何实时检查文本字段输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的文本框编写验证,我发现了一些有趣的东西,是否可以检查我实时输入到文本框中的数字。我的文本字段输入必须是8位数字。因此,当我达到8位数字时,我想将文本字段内的文本更改为绿色,而不是8位时更改颜色。



我该如何做?请帮助我,先谢谢。

解决方案

使用 -textField:shouldChangeCharactersInRange:replacementString:可能是一个坏的解决方案,因为它在文本字段更新之前触发。当您希望在键盘自动更新文本字段之前更改文本字段的文本时,应该使用此方法。这里,您可能希望在编辑值更改时只使用目标操作配对:

  [textField addTarget:self action:@selector (checkTextField :) forControlEvents:UIControlEventEditingChanged]; 

然后,在 - (void)checkTextField:(id)sender ,请尝试:

  UITextField * textField =(UITextField *)sender; 
if([textField.text length] == 8){
textField.textColor = [UIColor greenColor]; //没有货物要求,这种颜色很丑陋...
} else {
textField.textColor = [UIColor blackColor];
/ *必须完成,以防用户在添加8位数字,
或添加第九位数字后删除键* /
}
pre>

I am writing validation for my textfield, I found something interesting that whether I can check how many digits I am typing into the textfield at real time. My text field input must be 8 digit number. So I want to change the text inside the text field to green colour when I reach 8 digit and change colour when it's not.

How can I do that? Please help me, thanks in advance.

解决方案

Using -textField:shouldChangeCharactersInRange:replacementString: is probably a bad solution because it fires before the text field updates. This method should probably be used when you want to change the text of the text field before the keyboard automatically updates it. Here, you probably want to simply use target-action pairing when editing value changes:

[textField addTarget:self action:@selector(checkTextField:) forControlEvents:UIControlEventEditingChanged];

Then, in - (void)checkTextField:(id)sender, try this:

UITextField *textField = (UITextField *)sender;
if ([textField.text length] == 8) {
    textField.textColor = [UIColor greenColor]; // No cargo-culting please, this color is very ugly...
} else {
    textField.textColor = [UIColor blackColor];
    /* Must be done in case the user deletes a key after adding 8 digits,
       or adds a ninth digit */
}

这篇关于如何实时检查文本字段输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆