Current text selection in CustomKeyBoardExtension

余生颓废 提交于 2019-12-05 01:39:15

问题


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:


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.



来源:https://stackoverflow.com/questions/26030473/current-text-selection-in-customkeyboardextension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!