集成 Weex 到 iOS

使用 CocoaPods集成到iOS应用 - 图1 或 Carthage集成到iOS应用 - 图2 可以方便地将 Weex 集成到自己的项目中。

1. 配置依赖

使用 CocoaPods

从 Cocoapods 仓库集成到iOS应用 - 图3中获取 WeexSDK 的最新版本。 将 WeexSDK 添加到你的 Podfile 中。 1. source 'git@github.com:CocoaPods/Specs.git' 2. target 'YourTarget' do 3. platform :ios, '8.0' 4. pod 'WeexSDK', '0.20.1' 5. end

运行 pod install 命令安装依赖。

使用 Carthage

在工程中创建一个 Cartfile,Carthage 使用方法集成到iOS应用 - 图4。 添加 github "apache/incubator-weex" 到 Cartfile集成到iOS应用 - 图5 运行 carthage update。

2. 初始化 Weex

建议在 didFinishLaunchingWithOptions 回调中初始化 Weex,你也可以在子线程中异步初始化,但需要确保渲染 Weex 页面前初始化已经全部完成。 1. // App configuration 2. [WXAppConfiguration setAppGroup:@"Your app group"]; 3. [WXAppConfiguration setAppName:@"Your app name"]; 4. [WXAppConfiguration setAppVersion:@"Your app version"]; 5. 6. //Initialize WeexSDK 7. [WXSDKEngine initSDKEnvironment]; 8. 9. //Register custom modules and components, optional. 10. [WXSDKEngine registerComponent:@"myview" withClass:[MyViewComponent class]]; 11. [WXSDKEngine registerModule:@"mymodule" withClass:[MyWeexModule class]]; 12. 13. //Register the implementation of protocol, optional. 14. [WXSDKEngine registerHandler:[WXAppNavigationImpl new] withProtocol:@protocol(WXNavigationProtocol)]; 15. 16. //Set the log level, optional 17. [WXLog setLogLevel: WXLogLevelWarning];

3. 创建一个 Weex 实例

你既可以在全页面中使用 Weex,也可以在一个 view 中渲染 Weex。只需要创建一个 Weex 实例并指定好回调方法,提供一个合法的 URL 就可以了。在 onCreate 回调方法中将根 view 添加到你想显示内容的地方,并通过 instance.frame = 来设置它的尺寸和位置。 1. #import 2. 3. - (void)viewDidLoad 4. { 5. [super viewDidLoad]; 6. _instance = [[WXSDKInstance alloc] init]; 7. _instance.viewController = self; 8. _instance.frame = self.view.frame; 9. __weak typeof(self) weakSelf = self; 10. _instance.onCreate = ^(UIView *view) { 11. [weakSelf.weexView removeFromSuperview]; 12. weakSelf.weexView = view; 13. [weakSelf.view addSubview:view]; 14. }; 15. _instance.onFailed = ^(NSError *error) { 16. //process failure, you could open an h5 web page instead or just show the error. 17. }; 18. _instance.renderFinish = ^ (UIView *view) { 19. //process renderFinish 20. }; 21. NSURL *url = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"js"]; 22. [_instance renderWithURL:url options:@{@"bundleUrl":[self.url absoluteString]} data:nil]; 23. }

4. 销毁实例

必须显式地 销毁 Weex 实例,否则可能引起内存泄漏。 1. [instance destroyInstance];

5. 扩展 Weex

Weex 支持自定义组件、模块,可以参考以下两篇文档。 * Extend iOS * Extend iOS with swift

6. 在 iPad 中使用 Weex

当页面渲染完成后,屏幕再旋转,页面不会自动适配。所以,如果你的 App 允许屏幕旋转,务必在页面渲染前更新屏幕宽度。 前端样式中指定的坐标在渲染时会根据 屏幕宽度 和 当前页面的 view-port-width 进行换算。 修改 view-port-width 的方法,会影响前端代码,通常不要设置,默认为 750px。 1. beforeCreate(){ 2. const meta = weex.requireModule('meta'); 3. meta.setViewport({ 4. width: 1536 5. }); 6. }

监听 UIDeviceOrientationDidChangeNotification 通知,并调用下面方法修改屏幕尺寸(假设已经旋转完成,[UIScreen mainScreen].bounds.size.width 就是当前宽度) 1. [WXCoreBridge setDeviceSize:[UIScreen mainScreen].bounds.size];