Swift - 打开内置的iOS Dictionary来查找单词含义

时间:2015-09-16 08:51:20

标签: ios swift dictionary word

在我的项目中,我想打开 iOS内置词典来查找单词含义,甚至更好,直接在我的应用中获取单词的含义。

目前我发现如何使用 UITextChecker

检查字符串拼写是否正确
func wordIsReal(word: String) -> Bool {
    let checker = UITextChecker()
    let range = NSMakeRange(0, count(word))
    let misspelledRange = checker.rangeOfMisspelledWordInString(word, range: range, startingAt: 0, wrap: false, language: "en")

    return misspelledRange.location == NSNotFound
}

3 个答案:

答案 0 :(得分:5)

我找到了 Object-C 的解决方案:

if ([UIReferenceLibraryViewController    dictionaryHasDefinitionForTerm:@"word"]) {
    UIReferenceLibraryViewController* ref = 
    [[UIReferenceLibraryViewController alloc] initWithTerm:@"word"];
    [currentViewController presentViewController:ref animated:YES completion:nil];
}

我编辑了 Swift 3

let word = "home"
if UIReferenceLibraryViewController.dictionaryHasDefinitionForTerm(word) {
        let ref: UIReferenceLibraryViewController = UIReferenceLibraryViewController(term: word)
        self.presentViewController(ref, animated: true, completion: nil)
}

Swift 4 相同:

let word = "home"
if UIReferenceLibraryViewController.dictionaryHasDefinition(forTerm: word) {
    let ref: UIReferenceLibraryViewController = UIReferenceLibraryViewController(term: word)
    self.present(ref, animated: true, completion: nil)
}

如果单词在设备中保存的词典中有定义,则此解决方案允许打开内置词典

答案 1 :(得分:1)

试试这个

func wordIsReal(word: String) -> Bool {
    let checker = UITextChecker()
    let range = NSMakeRange(0, count(word))
    let misspelledRange = checker.rangeOfMisspelledWordInString(word, range: range, startingAt: 0, wrap: false, language: "en_US")
    NSLog("misspelledRange:\(misspelledRange)")
    NSLog("word:\(word)")
    var arrGuessed:NSArray? = checker.guessesForWordRange(misspelledRange, inString: word, language: "en_US")as NSArray!
  NSLog("arrGuessed:\(arrGuessed)")
    //var correctedStr = textAsNSString.stringByReplacingCharactersInRange(misspelledRange, withString: arrGuessed.objectAtIndex(0) as String)
    return misspelledRange.location == NSNotFound
}

答案 2 :(得分:0)

仅供参考:UIReferenceLibraryViewController.dictionaryHasDefinitionForTerm无法用于在您的应用上显示结果。那些词典提供者似乎只授权Apple使用其结果,而不授权任何第三方开发人员。您的应用将被拒绝:(