Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

iphone - Replacing Text in a UITextView

i'm trying to write a little concept app which reads the character stream as the user types in a UITextView, and when a certain word is entered it is replaced (sort of like auto-correction).

i looked into using -

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

but so far i had no luck. can anyone give me a hint.

greatly appreciated!

david

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That is the correct method. Is its object set as the delegate of the UITextView?

UPDATES:
-fixed above to say "UITextView" (I had "UITextField" previously)
-added code example below:

This method implementation goes in the delegate object of the UITextView (e.g. its view controller or app delegate):

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...