2009-10-27 7 views
3

J'essaye d'écrire une petite application de concept qui lit le flux de caractères pendant que l'utilisateur tape dans un UITextView, et quand un certain mot est entré il est remplacé (sorte de comme correction automatique).Remplacer du texte dans un UITextView

j'ai regardé à l'aide -

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

mais jusqu'à présent je pas eu de chance. Quelqu'un peut-il me donner un indice.

grandement apprécié!

david

+0

Êtes-vous l'un des txtView d'appel: shouldChangeTextInRange: replacementText :? – Malaxeur

Répondre

11

C'est la méthode correcte. Son objet est-il défini comme délégué du UITextView?

MISES À JOUR:
-Correction ci-dessus pour dire "UITextView" (j'avais "UITextField" précédemment)
Code -Ajout exemple ci-dessous:

Cette implémentation de la méthode va dans l'objet délégué du UITextView (par exemple son contrôleur de vue ou son délégué d'application):

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

tout est bien relié, je ne suis pas sûr de savoir comment utiliser cette méthode pour remplacer une chaîne donnée par une autre chaîne. Merci –