Current text selection in CustomKeyBoardExtension

2019-03-31 05:26发布

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 :(

1条回答
再贱就再见
2楼-- · 2019-03-31 05:36

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.

查看更多
登录 后发表回答