ios - 根据输入的字符限制 UITextField 在用户输入时显示的内容

标签 ios objective-c uitextfield

我想知道是否可以根据用户输入的字符限制 UITextField 显示的内容,他们正在输入。例如,我想排除字符“!”不会显示在 UITextField 中,因此当用户输入“Nice!”时,她在文本字段中看到的只是“Nice”,并且在“e”旁边有一个指示灯。

我曾尝试使用 shoudChangeCharactersInRange 并尝试了一些基本的操作,例如将所有输入的单词都变成小写,但没有成功。解决这个问题的最佳方法是什么,特别是如果我想完全保留一些字母或字符?谢谢

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    [self updateTextLabelsWithText: newString.lowercaseString];

    return YES;
}

最佳答案

更新的答案

好的,你能试试这个版本吗,看看它是否处理了额外粘贴带有无效字符的字符串?

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    BOOL shouldReplace = YES;

    NSRange invalidCharRange = [string rangeOfString:@"!"];

    if(invalidCharRange.length > 0)
    {
        shouldReplace = NO;

        NSString *cleanedString = [string stringByReplacingOccurrencesOfString:@"!" withString:@""];

        NSString *completeString = [[NSString alloc] initWithFormat:@"%@%@", textField.text, cleanedString];

        textField.text = completeString;
    }
    else
    {
        textField.text = [textField.text stringByReplacingOccurrencesOfString:@"!" withString:@""];
    }

    if([string isEqualToString:@"!"])
    {
        shouldReplace = NO;
    }

    return shouldReplace;
}

原始答案

如果替换字符串是“!”,只需设置 NO:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    BOOL shouldReplace = YES;

    if([string isEqualToString:@"!"])
    {
        shouldReplace = NO;
    }

    return shouldReplace;
}

关于ios - 根据输入的字符限制 UITextField 在用户输入时显示的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24544654/

相关文章:

objective-c - 如何禁用在 Xcode 中被标记为错误的警告

ios - 在 tableviewheader 中使用 UITextField 进行 self.view.endEditing 时崩溃

ios - iPhone:是否可以在点击 UITextField 时隐藏键盘?

ios - 一直跟踪 UIScrollView contentOffset

ios - 在 iOS 中设置全局变量后,我的应用程序崩溃了

ios - 使用 SwiftUI 时,接收有关 Split View 上应用程序之间焦点更改的通知

ios - 如何使用适用于 Apache Cordova 和 Xcode 8 的 Visual Studio 工具构建 iOS 应用程序

objective-c - iOS >> 应用内购买 : How to store data externally to the App Bundle?

ios - 这个示例代码让我定义了一些东西,但我还不想定义?

ios - swift 中单个对象的 NSNotification