Replacing text in a UITextView

I am trying to write a small conceptual application that reads a stream of characters when a user types in a UITextView, and when a specific word is entered, it is replaced (like auto-correction).

I looked at using -

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

but still I’m out of luck. can anyone give me a hint.

very grateful!

David

+3
source share
1 answer

This is the correct method. Is its object set as a UITextView delegate ?

UPDATE:
-fixed above to say “UITextView” (I used to have a UITextField)
the following code example:

- 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 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;
}
+11

Source: https://habr.com/ru/post/1721144/


All Articles