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

时间:2011-10-06 16:19:27

标签: iphone objective-c ios uitextfield uikeyboard

我正在编写应用程序,我需要将用户输入的文本验证到UITextField,char用char通过某种方法验证。

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

我知道UIControlEventEditingChanged等事件,但我仍然不知道两件事:

  • 如何在UITextField中看到之前用户输入的字符并执行验证

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

提前感谢您的帮助:)

2 个答案:

答案 0 :(得分:1)

实施UITextFieldDelegate方法textField:shouldChangeCharactersInRange:replacementString:,例如:

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

答案 1 :(得分:0)

类似于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];
}