2014-09-26 3 views
7

Как я могу реализовать интеллектуальную панель ввода Apple в своем собственном расширении клавиатуры iOS8?Как использовать автоматический запрос для пользовательского расширения клавиатуры ios8?

компании Apple на заказ Клавиатура API Doc Custom Keyboard состояние:

RequestsOpenAccess установить BOOL да в info.plist имеет доступ к основным autocorrection лексикону через класс UILexicon. Используйте этого класса вместе с лексикой вашего собственного дизайна, чтобы предоставить suggestions и autocorrections, поскольку пользователи вводят текст.

Но я не могу найти, как использовать UILexicon в моей пользовательской клавиатуре. Я установил RequestsOpenAccess установку для YES:

enter image description here

Но до сих пор не может получить доступ к пользовательскому словарю для предлагаемых слов, как iOS8 клавиатуры от Apple по умолчанию делает:

enter image description here

Мой пользовательский клавиатуры выглядят так:

enter image description here

EDIT:

я Найдено requestSupplementaryLexiconWithCompletion, который используется для UILexicon class как это я пытаюсь реализовать это, используя следующий код:

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    [self requestSupplementaryLexiconWithCompletion:^(UILexicon *appleLex) { 
     appleLexicon = appleLex; 
     NSUInteger lexEntryCount = appleLexicon.entries.count; 

     for(UILexiconEntry *entry in appleLexicon.entries) { 
      NSString *userInput = [entry userInput]; 
      NSString *documentText = [entry documentText]; 

      lable.text=userInput; 
      [lable setNeedsDisplay]; 
     } 
    }]; 
} 

ответ

8

Finlay я сделал это ..! я поставил предложение с использованием SQLite статической базы данных и получить первую три предлагаемую работу, используя как запрос, как следующий код:

NSString *precedingContext = self.textDocumentProxy.documentContextBeforeInput; //here i get enter word string. 



    __block NSString *lastWord = nil; 

    [precedingContext enumerateSubstringsInRange:NSMakeRange(0, [precedingContext length]) options:NSStringEnumerationByWords | NSStringEnumerationReverse usingBlock:^(NSString *substring, NSRange subrange, NSRange enclosingRange, BOOL *stop) { 
     lastWord = substring; 
     *stop = YES; 
    }]; 
    NSLog(@"==%@",lastWord); // here i get last word from full of enterd string 

    NSString *str_query = [NSString stringWithFormat:@"select * from suggestion where value LIKE '%@%%' limit 3",lastWord]; 
    NSMutableArray *suggestion = [[DataManager initDB] RETRIVE_Playlist:str_query]; 

    NSLog(@"arry %@",suggestion); i get value in to array using like query 
    if(suggestion.count>0) 
    { 

     if(suggestion.count==1) 
     { 
      [self.ObjKeyLayout.FirstButton setTitle:[suggestion objectAtIndex:0] forState:UIControlStateNormal]; 

     } 
     else if(suggestion.count==2) 
     { 
      [self.ObjKeyLayout.FirstButton setTitle:[suggestion objectAtIndex:0] forState:UIControlStateNormal]; 
      [self.ObjKeyLayout.secondButton setTitle:[suggestion objectAtIndex:1] forState:UIControlStateNormal]; 
     } 
     else 
     { 

      [self.ObjKeyLayout.FirstButton setTitle:[suggestion objectAtIndex:0] forState:UIControlStateNormal]; 
      [self.ObjKeyLayout.secondButton setTitle:[suggestion objectAtIndex:1] forState:UIControlStateNormal]; 
      [self.ObjKeyLayout.thirdButton setTitle:[suggestion objectAtIndex:2] forState:UIControlStateNormal]; 
     } 


    } 
    else 
    { 

     [self.ObjKeyLayout.FirstButton setTitle:@"" forState:UIControlStateNormal]; 
     [self.ObjKeyLayout.secondButton setTitle:@"" forState:UIControlStateNormal]; 
     [self.ObjKeyLayout.thirdButton setTitle:@"" forState:UIControlStateNormal]; 
    } 

и я получил это мой выход клавиатуры:

enter image description here

+0

Как вы заполнили таблицу SUGGESTION? Откуда у вас были все предложения? –

+0

Я упоминаю в своем ответе, что использовал статическую базу данных sqlite и используя LIKE-запрос, я получаю соответствующую работу с символом из базы данных sqlite. @StanleyKubrick –

+0

Эй, Нитин, где будет наш файл базы данных? в основном приложении или в расширении? – jamil

0

Может быть, этот ответом помогает кому-то.

+ (void)getSuggestionsFor:(NSString *)word WithCompletion:(void(^)(NSArray *))completion 
{ 
    NSString *prefix = [word substringToIndex:word.length - 1]; 
    // Won't get suggestions for correct words, so we are scrambling the words 
    NSString *scrambledWord = [NSString stringWithFormat:@"%@%@",word, [self getRandomCharAsNSString]]; 
    UITextChecker *checker = [[UITextChecker alloc] init]; 
    NSRange checkRange = NSMakeRange(0, scrambledWord.length); 
    NSRange misspelledRange = [checker rangeOfMisspelledWordInString:scrambledWord range:checkRange startingAt:checkRange.location wrap:YES language:@"en_US"]; 

    NSArray *arrGuessed = [checker guessesForWordRange:misspelledRange inString:scrambledWord language:@"en_US"]; 
    // NSLog(@"Arr ===== %@",arrGuessed); 
    // Filter the result based on the word 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",word]; 
    NSArray *arrayfiltered = [arrGuessed filteredArrayUsingPredicate:predicate]; 
    if(arrayfiltered.count == 0) 
    { 
     // Filter the result based on the prefix 
     NSPredicate *newPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",prefix]; 
     arrayfiltered = [arrGuessed filteredArrayUsingPredicate:newPredicate]; 
    } 
    completion(arrayfiltered); 
} 

+ (NSString *)getRandomCharAsNSString { 
    return [NSString stringWithFormat:@"%c", arc4random_uniform(26) + 'a']; 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^