4

I'm trying to write Custom Keyboard Extension.

I'm looking for the way to know where the cursor is on UITextField,UITextView...etc in CustomKeyboardExtension ... but I don't see anything like that.

I saw SwiftKey app (http://swiftkey.com) can do that (or do something like that). When I change the cursor, suggestion-text will change (see below pictures).

Q: How can we get current text selection?

...

UPDATE: 29/09/2014

Ok, I'm so foolish. We can use documentContextBeforeInput, documentContextAfterInput methods of textDocumentProxy property. I thought that "Before","After" are about the time. Actually it's about the position.

Sorry all! I wasted your time :(

Tony
  • 4,311
  • 26
  • 49
  • 2
    `textDocumentProxy.documentContextBeforeInput` – Thant Thet Sep 25 '14 at 16:08
  • 3
    Just 'documentContextBeforeInput' and 'documentContextAfterInput' don't cut it either. if the user opens a text that is auto selected, both will be empty, but there is definitely text in the field. – Bersaelor Feb 02 '15 at 17:45

1 Answers1

1

Create lastWordBeforeInput method...

-(NSString *) lastWordBeforeInput{
    NSArray *arrayOfSplitsString = [self.textDocumentProxy.documentContextBeforeInput componentsSeparatedByString:@" "];
    int countIndex = arrayOfSplitsString.count - 1;
    NSCharacterSet *ChSet = [NSCharacterSet alphanumericCharacterSet];
    NSCharacterSet *invertedChSet = [ChSet invertedSet];
    while (countIndex > 0) {
        NSString *lastWordOfSentance = [arrayOfSplitsString objectAtIndex:countIndex--];
        if ([[lastWordOfSentance stringByTrimmingCharactersInSet:invertedChSet] rangeOfCharacterFromSet:ChSet].location != NSNotFound) {
            return [lastWordOfSentance stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        }
    }

    return @"";
}

Then call it with textWillChange/textDidChange as per requirement.

- (void)textWillChange:(id<UITextInput>)textInput {
    // The app is about to change the document's contents. Perform any preparation here.
    NSLog(@"%@",[self lastWordBeforeInput]);
}

Hope this will help you.

Leo Moon85
  • 150
  • 10