0

我一直在试图找出一种方法来获取用户输入文本的建议列表(多种语言不是英语 en-US),我已经在这里发现了很多关于问题的讨论,但没有人想出整个解决方案,所以我试图执行以下场景:

1- 用户输入了一个或多个字母(例如“Ap”)

2-获取建议单词列表(例如Apple,Apply,...)

我应该如何获得此列表,例如自定义键盘应用程序(例如 Swift 键)

提前致谢。

4

1 回答 1

1

试试这个。

+ (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'];
}
于 2015-12-16T07:46:45.310 回答