ios - 如何过滤用户输入,使每个单词都有前缀

标签 ios objective-c cocoa-touch

我正在尝试通过标签创建搜索。用户可以输入单词。

现在我需要验证:

  • 用户每个词只有 1 个主题标签

  • 每个单词只有 1 个主题标签。

  • 如果单词不以主题标签开头,则添加一个。

  • 用户未输入超过1个空格,请删除多余的空格

  • 用户没有使用其他常见的分隔符来分隔单词,例如逗号或半逗号

我生成了以下代码,但是每次我开始一个新单词时,它都会删除两个单词之间的空格,并且不可能有两个单词,或者它只允许我有第二个单词,但它不会添加将 # 添加到第二个单词。

有人可以帮我解决验证的逻辑吗?

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

    // Delete double spaces between words
    NSString* str = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@" "];

    if ( [str isEqualToString:@""] ) {
        return YES;
    }

    // Check for other methods that people could use to separate strings
    str = [str stringByReplacingOccurrencesOfString:@"," withString:@"#"];
    str = [str stringByReplacingOccurrencesOfString:@";" withString:@"#"];

    // separate string by Hashtag
    NSArray * words = [str componentsSeparatedByString:@"#"];
    NSMutableArray * ma =[[NSMutableArray alloc]init];
    for (NSString* str4 in words) {
        if ( ![str4 isEqualToString:@""]) {
            // Separate string by space
            NSArray * words2 = [str4 componentsSeparatedByString:@" "];
            if ( [words2 count] != 0) {
                [ma addObjectsFromArray:words2];
            }
        }
    }
    words = [[NSArray alloc]initWithArray:ma];
    NSString * newStr = [[NSString alloc]init];

    // Make the new string
    for (NSString* str2 in words) {
        if ( ![str2 isEqualToString:@""]) {
            NSString* str3 = str2;
            str3 = [NSString stringWithFormat:@"#%@ ",str3];
            newStr = [newStr stringByAppendingString:str3];
        }
    }
    textField.text = newStr;
    return YES;
}

最佳答案

每次用户点击键盘上的按键或粘贴到文本字段时,都会调用您正在使用的委托(delegate)方法。

当调用时,文本字段的 text 属性仍然与用户点击按键之前相同。调用该方法来询问是否允许用户提出的更改进入该字段。所以,你的方法有几个问题:

  • 在实际进行更改之前,您将对文本字段的内容执行所有验证,因此您实际上将验证上一次按键时输入的内容。您可以通过在委托(delegate)方法开始时自行进行更改并对新字符串执行验证来克服此问题:

    NSString *proposedText = [textField.text stringByReplacingCharactersInRange:range withString:replacementString];
    
  • 您将返回 YES,表示可以进行建议的更改,并更新文本字段的文本值。这意味着建议的更改可能会发生在您刚刚更新的值上。如果您自己在此方法中设置文本,请返回 NO

关于ios - 如何过滤用户输入,使每个单词都有前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18053950/

相关文章:

iphone - UIManagedDocument 和核心数据

ios - 收到 SUbiquity Identity DidChangeNotification 后我应该做什么?

ios - 自定义委托(delegate)有问题

ios - 需要在类似最近联系人的App图标上实现3D touch

cocoa-touch - 手势识别器在 iOS 4.3 中停止工作

ios - 为什么 NSMutableDictionary 丢失数据?

ios - 具有双向绑定(bind)的自定义 SwiftUI View

ios - 如何重置 NSTextStorage 中的属性

ios - 如何在 UITableView 的选定单元格行中设置图像

objective-c - 多 View iOS 应用程序的约定