Apple 的文档中似乎有一些引用资料,但我在任何组件中都没有看到这一点(例如在此处列出)。
因为这似乎是一个非常标准的功能,我觉得我只是缺少一些基本的东西。这也不是最容易搜索的东西。
这里是Apple的sdk文档 https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIReferenceLibraryViewControllerClassRef/index.html
最佳答案
如您所知,要使用 native 代码,您需要创建一个 native 模块。
这是如何......
首先在 Xcode 中添加一个新文件:
文件 > 新建文件 > Cocoa Touch 类。 确保将其设置为 NSObject 的子类。例如,将其命名为 ReferenceLibraryManager。
在头文件(.h)中:
你只需要实现 RCTBridgeModule
协议(protocol):
#import "RCTBridgeModule.h"
@interface ReferenceLibraryManager : NSObject <RCTBridgeModule>
@end
在方法文件(.m)中:
您需要实现并公开一个可以从 JS 中调用的本地方法,如下所示:
#import "ReferenceLibraryManager.h"
#import <UIKit/UIReferenceLibraryViewController.h>
#import "AppDelegate.h"
@implementation ReferenceLibraryManager
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(showDefinitionForTerm:(NSString*)term callback:(RCTResponseSenderBlock)callback)
{
if (callback == nil)
return;
BOOL hasDefinition = NO;
if ([UIReferenceLibraryViewController dictionaryHasDefinitionForTerm:term])
{
hasDefinition = YES;
dispatch_async(dispatch_get_main_queue(), ^{
UIReferenceLibraryViewController *referenceLibraryVC = [[UIReferenceLibraryViewController alloc] initWithTerm:term];
UIViewController *rootVC = ((AppDelegate*)[UIApplication sharedApplication].delegate).window.rootViewController;
[rootVC presentViewController:referenceLibraryVC animated:YES completion:nil];
});
}
callback(@[@(hasDefinition)]);
}
@end
需要注意的一些有趣的事情:
- 为了能够像我们在这里做的那样呈现一个“ View Controller ”,您需要另一个 View Controller 来呈现它。上面的代码使用 应用程序的“ Root View Controller ”。它应该适用于大多数人 案例,但这也取决于您的应用程序的结构。
- React native 不会在主线程上调用原生组件方法。在处理与 UI 相关的任何事情时,您必须在主线程上进行,因此要在主线程中使用
dispatch_async
。
JavaScript 部分:
您导入 native 模块并使用它..
var React = require('react-native');
var ReferenceLibraryManager = React.NativeModules.ReferenceLibraryManager;
....
var term = "React";
ReferenceLibraryManager.showDefinitionForTerm(term, (hasDefinition) => {
if(!hasDefinition) {
alert('definition not found...');
}
})
顺便说一句 - 您可以在 react native docs 上找到创建 native 模块的完整指南和示例。 .
关于ios - React Native 如何访问 iOS 字典来提取单词的定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33771639/