[ios]阻止在 shouldChangeTextInRange 期间删除前缀

标签: UITextView ios
发布时间: 2015/7/5 11:56:28
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有 UITextView ,都有一个前缀包含一个 4 字符空格字符串作为缩进。如果我键入大量的文本,然后按住 backspace 按钮约一秒钟,它将删除文本速度快字对字的但它还会删除我的"分离器空间",从而导致我 UITextView 要卡住,不能再键入。

这是我讲的捕捉:

if (range.location <= 4 && textView == self.descriptionTextView) {
    #warning fast deletion causes this to be un-editable
    return NO; // makes sure no one can edit the first 4 chars
}

如何防止这种"快速删除"以及删除"分离空间"?

解决方法 1:

为了维护您的前缀,我建议找出字符串,会导致你要是事实上改变在给定的范围内,字符,然后只允许对该文本进行更改如果前缀不保持原样;例如,在您的具体情况:

- (BOOL)textView:(UITextView *)textView shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    // Combine the new text with the old
    NSString *combinedText = [textView.text stringByReplacingCharactersInRange:range withString:string];

    // If the user attempts to delete before the 4th
    // character, delete all but the first 4 characters
    if (combinedText.length < 4) {
        textView.text = @"    "; // <-- or whatever the first 4 characters are
        return NO;
    }

    // Else if the user attempts to change any of the first
    // 4 characters, don't let them
    else if (![[textView.text substringToIndex:4] isEqualToString:[combinedText substringToIndex:4]]) {
        return NO;
    }

    return YES;
}

或更广泛地说,若要允许的灵活性,你可以将你的前缀字符串存储为一个类的实例变量然后基地你 shouldChangeCharactersInRange: 上无论该前缀变量可能的代码:

- (BOOL)textView:(UITextView *)textView shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    // Combine the new text with the old
    NSString *combinedText = [textView.text stringByReplacingCharactersInRange:range withString:string];

    // If the user attempts to delete into the prefix
    // character, delete all but the prefix
    if (combinedText.length < self.prefixString.length) {
        textView.text = self.prefixString;
        return NO;
    }

    // Else if the user attempts to change any of the prefix,
    // don't let them
    else if (![self.prefixString isEqualToString:[combinedText substringToIndex:self.prefixString.length]]) {
        return NO;
    }

    return YES;
}
官方微信
官方QQ群
31647020