Swift-打开内置的iOS词典以查找单词含义

Ric*_*oCh 4 dictionary cpu-word ios swift

在我的项目中,我想打开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
}
Run Code Online (Sandbox Code Playgroud)

Ric*_*oCh 7

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

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

并且我已经为Swift 3编辑了它:

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

Swift 4相同:

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

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

  • 有没有办法在 Mac 上做到这一点(没有 uikit)? (2认同)