【问题标题】:Swift - open built-in iOS Dictionary to find word meaningSwift - 打开内置的 iOS 词典以查找词义
【发布时间】:2015-12-12 18:11:55
【问题描述】:

在我的项目中,我想打开 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
}

【问题讨论】:

标签: ios swift dictionary word


【解决方案1】:

我找到了 Objective-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)
}

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

【讨论】:

  • 有没有办法在 Mac 上做到这一点(没有 uikit)?
  • 经过测试。它在iOS14中工作。需要一个预先下载的字典来呈现视图。
【解决方案2】:

试试这个

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 2016-12-30
    • 2012-04-15
    • 2014-05-25
    相关资源
    最近更新 更多