在一个UITextView替换文本(Replacing Text in a UITextView)

2019-09-01 09:52发布

我试图写一个小程序的概念读取字符流作为一个UITextView中的用户类型,并输入某个词,当它被替换(有点像自动校正)。

我看着使用 -

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

但到目前为止,我没有运气。 任何人都可以给我一个提示。

非常感激!

大卫

Answer 1:

这是正确的方法。 是它的对象设置为UITextView中的代表?

更新:
-fixed上面说“的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;
}


文章来源: Replacing Text in a UITextView