繁体   English   中英

在UITextField中显示字符之前如何访问用户键入的字符

[英]How to access character typed by user before showing it in UITextField

我正在编写应用程序,在其中我需要使用某种方法来验证用户输入到UITextField字符,一个字符一个字符。

困难的是,客户希望在用户看到UITextField中的字符之前进行所有验证,因为可能存在服务器应用程序不支持'$'符号的情况,因此在我的验证方法中,应将其替换为'USD'字符串-他不希望用户看到'$' ,只是立即看到'USD'

我知道类似UIControlEventEditingChanged事件,但我仍然不知道2件事:

  • 如何在UITextField看到字符之前访问用户键入的字符并在那里执行验证

  • 如何“动态”替换此字符并将其手动放置到UITextField(但我想我只是将其附加到[[textField] text] NSString

预先感谢您的任何帮助 :)

实现UITextFieldDelegate方法textField:shouldChangeCharactersInRange:replacementString:例如:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    BOOL validated = ...; //do your validation
    return validated;
}

与omz的答案类似,但如果需要,可以提供更完整的代码:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

    NSString *filtered;
    filtered = [string stringByReplacingOccurrencesOfString:@"$" withString:@"USD"];

    //optionally if you want to only have alphanumeric characters
    //NSMutableCharacterSet *mcs1 = [[[NSCharacterSet letterCharacterSet] invertedSet] mutableCopy];  //only alphabet character
    //[mcs1 removeCharactersInString:@"0123456789"];  
    //filtered = [[filtered componentsSeparatedByCharactersInSet:mcs1] componentsJoinedByString:@""];
    //release mcs1;

    return [string isEqualToString:filtered];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM