有点好玩,所以我刚才写了代码。该代码有效。
首先,我们应该设置 UITextView 的委托并响应 .
textView:shouldChangeTextInRange:replacementText:
根据文件,
如果用户按下 Delete 键,则范围的长度为 1,并且一个空字符串对象替换该单个字符。
所以代码如下:
#pragma mark -
#pragma mark - UITextView Delegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
static NSString *suffix = @"e";
if (range.length == 1 && [text length] == 0) {
// The user presses the Delete key.
NSString *currentText = [textView.text substringToIndex:range.location+1];
NSString *appendingText = [textView.text substringFromIndex:range.location+1];
if ([currentText hasSuffix:suffix]) {
NSRange range = [self inverseRangeOfString:currentText withSuffix:suffix];
currentText = [currentText stringByReplacingCharactersInRange:range withString:@""];
textView.text = [currentText stringByAppendingString:appendingText];
return NO;
}
}
return YES;
}
- (NSRange)inverseRangeOfString:(NSString *)str withSuffix:(NSString *)suffix
{
int length = [str length];
int lastIndex = length - 1;
int cnt = 0;
for (; lastIndex >= 0; --lastIndex) {
NSString *subStr = [str substringFromIndex:lastIndex];
if ([subStr hasPrefix:suffix]) {
cnt++;
} else {
break;
}
}
NSRange range = (NSRange){++lastIndex, cnt};
return range;
}