在shouldChangeTextInRange期间防止删除前缀

我有一个UITextView有一个前缀包含一个4字符的空白string作为缩进。 如果我键入大量文本,然后按住退格button一秒钟左右,它会逐字逐句删除文本,但也会删除我的“分隔符空间”,从而导致我的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 } 

如何防止这种“快速删除”删除“分隔空间”呢?

为了保持你的前缀,我build议搞清楚如果你实际上改变给定范围内的字符会导致的string,然后只允许文本改变,如果前缀不保持原样; 例如,在你的具体情况下:

 - (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; } 

或者更一般地说,为了保持灵活性,您可以将前缀string存储为类实例variables,然后根据前缀variables可能存在的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; }