Swift - 打开内置 iOS 词典来查找单词意思

本年度 App Store 十佳 App Pin 里面有一个功能是调用内置词典来查询剪贴板中的单词,在我的项目里我也想打开 iOS 内置词典来查询单词含义。

下面是解决方案:

  • Objective-C
    if ([UIReferenceLibraryViewController dictionaryHasDefinitionForTerm:@"word"]) {
    UIReferenceLibraryViewController* ref =
    [[UIReferenceLibraryViewController alloc] initWithTerm:@"word"];
    [currentViewController presentViewController:ref animated:YES completion:nil];
    }
  • Swift
    let word = "home"
    if UIReferenceLibraryViewController.dictionaryHasDefinitionForTerm(word) {
    let ref: UIReferenceLibraryViewController = UIReferenceLibraryViewController(term: word)
    self.presentViewController(ref, animated: true, completion: nil)
    }

这种行为和用户点击UITextView中高亮词汇弹出的"定义"的UIMenuItem的效果差不多。

UIReferenceLibraryViewController也提供了一个类方法dictionaryHasDefinitionForTerm:,开发者可以在dictionary view controller出现之前调用这个方法,就可以在不必需的时候不显示那个view controller了。

[UIReferenceLibraryViewController dictionaryHasDefinitionForTerm:@"apple"];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容