YownYang's blog

iOS-Weex的简单使用

本篇主要讲解一下Weex的大概原理以及简单的使用

Weex

  • 与RN相同原理,某些方面优于RN
  • js语法,比Native体验稍差,比hybrid app体验好太多
  • js一端代码,三端使用
  • iOS/Android脱离写UI的噩梦
  • 文档不够完善

Weex原理

Weex使用

  • 首先,在AppDelegate中调用[WXSDKEngine initSDKEnvironment]进行注册
1
2
3
4
5
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[WXSDKEngine initSDKEnvironment];
return YES;
}
  • 其次,在需要使用的ViewController中定义一个WXSDKInstance实例和UI个UIView实例
1
2
@property (nonatomic) WXSDKInstance *instance;
@property (nonatomic) UIView *weexView;
  • 紧接着,初始化WXSDKInstance实例,设置它的viewController、frame属性,实现它的生命周期
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
_instance = [[WXSDKInstance alloc] init];
_instance.viewController = self;
_instance.frame = [UIScreen mainScreen].bounds;
__weak typeof(self) weakSelf = self;
_instance.onCreate = ^(UIView *view) {
[weakSelf.weexView removeFromSuperview];
weakSelf.weexView = view;
[weakSelf.view addSubview:weakSelf.weexView];
};
_instance.onFailed = ^(NSError *error) {
NSLog(@"failed %@",error);
};
_instance.renderFinish = ^(UIView *view) {
NSLog(@"render finish");
};
_instance.onRenderProgress = ^(CGRect renderRect) {
NSLog(@"renderProgress");
};
_instance.updateFinish = ^(UIView *view) {
NSLog(@"update Finish");
};
  • 最后,使用WXSDKInstance实例调用renderWithURL:方法即可。记得在dealloc中释放WXSDKInstance实例哦😯

[self.instance renderWithURL:[NSURL URLWithString:renderURL]];

Weex的自定义

  • Component: Weex组件,weex官方基本把原生的定义过了,所以你基本不需要自定义。如果需要自定义,普通组件继承WXComponent,滑动组件继承WXScrollerComponent
  • handler: Native提供一个协议。weex官方定义了常用的部分,如WXImgLoaderProtocol图片下载。如果需要自定义,注意需遵守协议WXModuleProtocol
  • module:js调用Native, 返回值可有可无。这个基本用到就是自定义,遵守协议WXModuleProtocol,需要自定义Method,如果需要返回值使用WXModuleCallback返回
  • 总结:Component、handler、module都需要在使用前进行注册,一般都是在AppDelegate中,如下:
1
2
3
[WXSDKEngine registerModule:@"test" withClass:[WeexCustomModule class]];
[WXSDKEngine registerModule:@"user" withClass:[HMBUserModule class]];
[WXSDKEngine registerHandler:[HMBWeexImageLoader new] withProtocol:@protocol(WXImgLoaderProtocol)];

基本的Weex知识就是这些,具体使用方法请参照官方文档和demo链接
下篇开始讲解weex源码,未使用过weex的建议先尝试使用weex。