我有一个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
}
如何防止这种“快速删除”同时删除“分隔空间”?
答案 0 :(得分:1)
为了保持你的前缀,我建议你找出如果你实际上改变了给定范围内的字符会导致的字符串,然后只允许在前缀没有的情况下改变文本。 #39;保持原样;例如,在您的特定情况下:
- (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;
}