[TOC]

Example Initialize the Weex environment

  • WXSDKEngine: Most of the interfaces that the SDK opens up are declared here.
  • WXLog: Controls the level of Log output, including Verbose, Debug, Info, Warning, and Error. Developers can set the output level as required.
  • WXDebugTool: external debugging tool provided by weeX.
  • WXAppConfiguration: service configuration developed using WEEX.

The AppDelegate didFinishLaunchingWithOptions method to initialize the Settings

// Service configuration, optional [WXAppConfiguration]setAppGroup:@"itheimaApp"];
[WXAppConfiguration setAppName:@"WeexDemo"];
[WXAppConfiguration setAppVersion:@"3.2.0"]; // Initialize the 'WeexSDK' environment [WXSDKEngine initSDKEnviroment]; // Register custom components and models, optional [register if you have one, don't register if you don't] [WXSDKEngine registerComponent:@"YourView" withClass:[MyViewComponent class]];
[WXSDKEngine registerModule:@"YourModule"withClass:[YourModule class]]; // Register protocol implementation class, Optional [WXSDKEngine registerHandler:[WXNavigationDefaultImpl new] withProtocol:@protocol(WXNavigationProtocol)]; // Set the Log output level: The debugging environment is Debug by default, and formal briefings are automatically disabled. [WXLogsetLogLevel:WXLogLevelDebug];
Copy the code

Render Weex instances

  1. Declare the attribute instance
// WXSDKInstance @property (nonatomic, strong) WXSDKInstance *weexInstance; @property (weak, nonatomic) UIView *weexView;Copy the code
  1. Create the WXSDKInstance object and set it up. WXSDKInstance is an instance object rendered by WEEx. It provides developers with many interfaces related to page rendering, including renderWithURL, refreshInstance, and destroyInstance. It also provides several important callback interfaces for developers to deal with their logic according to different business scenarios, such as onfailed. Interfaces related to performance monitoring are also provided.
- (void)renderWeexWithURL:(NSString *)url {// create WXSDKInstance _weexInstance = [[WXSDKInstance alloc] init]; / / set the weexInstance controller by _weexInstance. ViewController = self; // Set weexInstance's frame _weexinstance. frame = self.view.frame; __weak typeof(self) weakSelf = self; _weexInstance.onCreate = ^(UIView *view) {weakself. weexView = view; [weakSelf.weexView removeFromSuperview]; [weakSelf.view addSubview:weakSelf.weexView]; }; OnFailed = ^(NSError *error) {// Process failure NSLog(@)"Processing failed :%@",error); }; / / set the render complete callback _weexInstance. RenderFinish = ^ (UIView * view) {/ / process renderFinish NSLog (@"Render complete"); }; // Set the URL path of weexInstance renderWithURL: URL options:@{@"bundleUrl":[self.url absoluteString]} data:nil]; } // We need to destroy WeexInstance in the dealloc method of the controller otherwise memory will leak - (void)dealloc {// Destroy WXSDKInstance [self.instance destroyInstance]; }Copy the code

Load the Weex JS file

The WEEX JS files are usually loaded from the server. If you do not want to load the WEEX JS files from the server, you can copy the JS files to the project directory.

  1. Generate the WEEX JS file using the. We file

    terminalcdGo to the directory where the.we file is located, and execute
weex  list.we -o list.js
Copy the code

Where list.we is the weeX file corresponding to your page. In development index.we generally refers to the entry file that uses the entire App. Here we use the list.we file to generate a list.js file

  1. URL of the js file
// Load the js file [_instance renderWithURL:[[NSBundle mainBundle] URLForResource:@"list"   withExtension:@"js"]].Copy the code
// Load js file from server [_instance renderWithURL:[NSURL URLWithString:@"http://10.0.100.139:8081/weex.js"]].Copy the code

Weex developed component skeleton and life cycle

<template>
</template>

<style>
</style>

<script>
  module.exports = {
    data: {},
    methods: {},

    init: function () {
      console.log('Fired after initializing an internal variable and adding an event function');
    },
    created: function () {
      console.log('Triggered before template compilation after data binding');
    },
    ready: function () {
      console.log('Triggered after the template has compiled and generated the Virtual DOM');
    },
    destroyed: function () {
      console.log('Called when the page is destroyed');
    }
  }
</script>
Copy the code
  • The template is mainly a reference to the component, the general layout of the page. Similar to HTML.
  • Style is the component’s CSS style reference
  • Script is basically js calls. – data Indicates bound data. Init, created, and Ready are Weex life cycle methods.
  • Methods holds user-defined JS events.
  • In computed, the data part of the binding data is preprocessed.
  • Init is usually used to initialize some internal variables and bind some custom events. At this time, there is no data binding and vDOM has not been created. Therefore, data and methods cannot be obtained through this, and nodes of vDOM cannot be obtained
  • Created completes data binding, but has not yet started compiling templates. Data and methods can be obtained through this, but nodes of the VDOM cannot be obtained through this
  • Ready indicates that the rendering is complete and triggers from the child component upwards
  • Destroyed component destruction, such as page jumps, is triggered upward from the child component

Template Module extension

1. Customize the Module

  1. The custom Module class must be implementedWXModuleProtocol
  2. Macros must be addedWX_EXPORT_METHOIn order for it to be recognized by WEEx, it takes the argument == of the method specified by the JavaScript call module
  3. add@synthesized weexInstanceEach moudle object is bound to a specified instance
  4. The Module method will be called in the UI thread, so don’t do too many time-consuming tasks here. If you want to execute the entire Module method in another thread, you need to implement the WXModuleProtocol – (NSThread *)targetExecuteThread method. In this case, Tasks assigned to this Module will run in the specified thread
  5. The Weex parameter can be String or Map
  6. Module supports returning values to JavaScript callbacks of type WXModuleCallback, which can be String or Map
@implementation WXEventModule
@synthesize weexInstance;
WX_EXPORT_METHOD(@selector(openTLDURL:callback))
- (void)openTLDURL:(NSString *)url callback:(WXModuleCallback)callback {
    NSString *newURL = url;
    if ([url hasPrefix:@"/ /"]) {
        newURL = [NSString stringWithFormat:@"http:%@", url];
    } else if(! [url hasPrefix:@"http"]) {
       newURL = [NSURL URLWithString:url relativeToURL:weexInstance.scriptURL].absoluteString;
    }
    UIViewController *controller = [[WXDemoViewController alloc] init];
    ((WXDemoViewController *)controller).url = [NSURL URLWithString:newURL];
    [[weexInstance.viewController navigationController] pushViewController:controller animated:YES];
    callback(@{@"result": @"success"});
}
@end
Copy the code

2. Register this Module

Register your module by calling the registerModule:withClass method in WXSDKEngine

[WXSDKEngine registerModule:@"tldevent" withClass:[WXEventModule class]];
Copy the code

3. Use this Module

The tldevent in require is the name of the registerModule registration module that was called in the previous step

var eventModule = weex.requireModule('tldevent'); 
eventModule.openTLDURL('url'.function(ret) {   
    nativeLog(ret);
});
Copy the code

Components extension

There are a lot of native components in the WeexSDK, but that may not be enough. If you’ve written some cool native components before and want to package them and import them into Weex, you can implement your own Native Component. (See the WXSelectComponent of WeexPlayGround in the official source.)

1. Custom components

Implementation WXMyComponent WX_EXPORT_METHOD(@selector(tldfocus)) // exposes the method to js - (instancetype)initWithRef:(NSString) *)reftype:(NSString *)typestyles:(NSDictionary *)styles attributes:(NSDictionary *)attributes events:(NSArray *)events weexInstance:(WXSDKInstance  *)weexInstance {if (self = [super initWithRef:ref type:typestyles:styles attributes:attributes events:events weexInstance:weexInstance]) { // handle your attributes // handle your  styles }return self;
}
- (void)tldfocus
{
    NSLog(@"you got it");
}
@end
Copy the code

2. Register components

[WXSDKEngine registerComponent:@"mycomponent" withClass:[WXMyComponent class]]
Copy the code

3. Use of components

<template>
  <mycomponent id='mycomponent'></mycomponent>
</template>
<script>
  module.exports = {
    created:function() {
      this.$el('mycomponent').tldfocus();
    }
  }
</script>
Copy the code

Implementation of the protocol (Handler)

Weex SDK does not have the ability of image downloading and navigation operation, so it needs to implement these protocols by itself

1. Implementation protocol (Taking WXImgLoaderProtocol as an example)

#pragma mark - WXImgLoaderProtocol
- (id<WXImageOperationProtocol>)downloadImageWithURL:(NSString *)url imageFrame:(CGRect)imageFrame userInfo:(NSDictionary *)userInfo completed:(void(^)(UIImage *image,  NSError *error, BOOL finished))completedBlock
{
    if ([url hasPrefix:@"/ /"]) {
        url = [@"http:" stringByAppendingString:url];
    }
    return (id<WXImageOperationProtocol>)[[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:url] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {     
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
    if(completedBlock) { completedBlock(image, error, finished); }}]; }Copy the code

2. Handler registration

[WXSDKEngine registerHandler:[WXImgLoaderDefaultImpl new] withProtocol:@protocol(WXImgLoaderProtocol)]

Copy the code

Tips

  1. Weex was rendered with a width of 750 pixels, and then scaled in equal proportion to the actual width of the screen. As a result, the Height of the Plus series will be larger and the display will not open, and the height of the 5 series will be smaller and the bottom will be blank. I calculated the zoom multiple according to the actual screen width and scale, and then set the actual height. I don’t know if there is any other good processing method. (This will also be the case with fonts that are smaller on the 5 series and larger on the Plus series)
    var config  = this.$getConfig(a); var env = config.env; var scale = env.scale; this.realScale = 750/2*scale/env.deviceWidth this.rowHeight = this.rowHeight * this.realScale;Copy the code