【问题标题】:Replacing Text in a UITextView替换 UITextView 中的文本
【发布时间】:2009-10-27 02:15:35
【问题描述】:

我正在尝试编写一个小的概念应用程序,它在用户在 UITextView 中键入时读取字符流,并且当输入某个单词时,它会被替换(有点像自动更正)。

我研究过使用 -

(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;

但到目前为止我没有运气。谁能给我一个提示。

非常感谢!

大卫

【问题讨论】:

  • 你是那个调用 txtView:shouldChangeTextInRange:replacementText:?

标签: iphone cocoa-touch


【解决方案1】:

这是正确的方法。它的对象是否设置为 UITextView 的委托?

更新:
- 固定在上面说“UITextView”(我之前有“UITextField”)
-在下面添加代码示例:

这个方法实现进入 UITextView 的委托对象(例如它的视图控制器或应用程序委托):

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

【讨论】:

  • 一切都很好,我只是不确定如何使用这种方法将给定的字符串替换为另一个字符串。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-27
  • 2012-02-22
  • 1970-01-01
  • 1970-01-01
  • 2012-02-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多