Search code examples
objective-ciosuitextviewuimenucontroller

UITEXTVIEW: Get the recent word typed in uitextview


I want to get the most recent word entered by the user from the UITextView.

The user can enter a word anywhere in the UITextView, in the middle or in the end or in the beginning. I would consider it a word when the user finishes typing it and presses a space and does any corrections using the "Suggestions from the UIMenuController".

Example: User types in "kimd" in the UITextView somewhere in the middle of text, he gets a popup for autocorrection "kind" which he does. After he does that, I want to capture "kind" and use it in my application.

I searched a lot on the internet but found solutions that talk about when the user enters text in the end. I also tried detecting a space and then doing a backward search until another space after some text is found, so that i can qualify it as a word. But I think there may be better ways to do this.

I have read somewhere that iOS caches the recent text that we enter in a text field or text view. If I can pop off the top one , that's all I want. I just need handle to that object.

I would really appreciate the help.

Note: The user can enter text anywhere in UItextview. I need the most recent entered word

Thanks.


Solution

  • //This method looks for the recent string entered by user and then takes appropriate action.
    
         - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
     //Look for Space or any specific string such as a space
    if ([text isEqualToString:@" "]) {
    NSMutableCharacterSet *workingSet = [[NSCharacterSet whitespaceAndNewlineCharacterSet]   mutableCopy];
    
      NSRange newRange = [self.myTextView.text rangeOfCharacterFromSet:workingSet
                                         options:NSBackwardsSearch
                                         range:NSMakeRange(0, (currentLocation - 1))];
    
     //The below code could be done in a better way...
     UITextPosition *beginning = myTextView.beginningOfDocument;
     UITextPosition *start = [myTextView positionFromPosition:beginning offset:currentLocation];
     UITextPosition *end = [myTextView positionFromPosition:beginning   offset:newRangeLocation+1];
     UITextRange *textRange = [myTextView textRangeFromPosition:end toPosition:start];
    
     NSString* str = [self.myTextView textInRange:textRange]; 
    }
    }