Iphone 替换UITextView中的文本
我正在尝试编写一个小概念应用程序,当用户在UITextView中键入字符流时,它会读取字符流,当输入某个单词时,它会被替换(有点像自动更正) 我研究了使用-Iphone 替换UITextView中的文本,iphone,cocoa-touch,Iphone,Cocoa Touch,我正在尝试编写一个小概念应用程序,当用户在UITextView中键入字符流时,它会读取字符流,当输入某个单词时,它会被替换(有点像自动更正) 我研究了使用- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text; 但到目前为止,我没有运气。谁能给我一个提示吗 非常感谢 大卫:这是正确的方法。其对象是否设置为UITextView的委
(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
但到目前为止,我没有运气。谁能给我一个提示吗
非常感谢
大卫:这是正确的方法。其对象是否设置为UITextView的委托 更新:
-修正了上面的“UITextView”(我以前有“UITextField”)
-下面添加了代码示例: 此方法实现位于UITextView的委托对象中(例如,其视图控制器或应用程序委托):
您是调用txtView:shouldChangeTextInRange:replacementText:?一切都连接好了,我只是不知道如何使用此方法将给定字符串替换为另一个字符串。谢谢
// replace "hi" with "hello"
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
// create final version of textView after the current text has been inserted
NSMutableString *updatedText = [[NSMutableString alloc] initWithString:textView.text];
[updatedText insertString:text atIndex:range.location];
NSRange replaceRange = range, endRange = range;
if (text.length > 1) {
// handle paste
replaceRange.length = text.length;
} else {
// handle normal typing
replaceRange.length = 2; // length of "hi" is two characters
replaceRange.location -= 1; // look back one characters (length of "hi" minus one)
}
// replace "hi" with "hello" for the inserted range
int replaceCount = [updatedText replaceOccurrencesOfString:@"hi" withString:@"hello" options:NSCaseInsensitiveSearch range:replaceRange];
if (replaceCount > 0) {
// update the textView's text
textView.text = updatedText;
// leave cursor at end of inserted text
endRange.location += text.length + replaceCount * 3; // length diff of "hello" and "hi" is 3 characters
textView.selectedRange = endRange;
[updatedText release];
// let the textView know that it should ingore the inserted text
return NO;
}
[updatedText release];
// let the textView know that it should handle the inserted text
return YES;
}