我有一个 UITextView
,它有一个包含 4 个字符的空白字符串作为缩进的前缀。如果我输入大量文本然后按住退格键大约一秒钟,它会逐字逐句快速删除文本,但它也会删除我的“分隔符空格”,这会导致我的 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
}
如何防止这种“快速删除”也删除“分隔空间”?
最佳答案
为了维护您的前缀,我建议找出如果您实际上更改给定范围内的字符会产生的字符串,然后只允许在前缀不更改时更改文本保持原样;例如,在您的特定情况下:
- (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;
}
或者更一般地说,为了实现灵 active ,您可以将前缀字符串存储为类实例变量,然后将您的 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;
}
关于ios - 防止在 shouldChangeTextInRange 期间删除前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27673079/