美文网首页iOS开发
iOS-Echarts的简单应用

iOS-Echarts的简单应用

作者: SmileYang966 | 来源:发表于2020-05-11 18:46 被阅读0次

1. 效果图

用户点击红色按钮,即显示扇形图


oc调用echarts.png

2. 设计思路

2.1 创建一个index.html,引入echarts库文件。编写js测试函数test1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <script src="./echarts.min.js"></script>
</head>
<body>
    <div id="main" style="width: 800px;height: 800px;background-color: azure"></div>
    <script type="text/javascript">
        function test1(option)
        {
            // 基于准备好的dom,初始化echarts实例
            var myChart = echarts.init(document.getElementById('main'));
            // 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option);
        }
    </script>
</body>
</html>

2.2 在OC界面,需要使用wkwebView去访问html资源,并和步骤1创建的js函数进行交互
懒加载一个wkwebView对象

- (WKWebView *)webView{
    if (_webView == nil) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0,0,200,200) configuration:config];
        _webView.allowsBackForwardNavigationGestures = YES;
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        _webView.center = self.view.center;
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
        NSString *htmlStr = [[NSString alloc]initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        [_webView loadHTMLString:htmlStr baseURL:[[NSBundle mainBundle] bundleURL]];
        
        [self.view addSubview:_webView];
    }
    return _webView;
}

懒加载一个button

- (UIButton *)button{
    if (_button == nil) {
        _button = [[UIButton alloc]initWithFrame:CGRectMake(30,30,200,40)];
        _button.backgroundColor = [UIColor redColor];
        [_button setTitle:@"显示简单的扇形图" forState:UIControlStateNormal];
        [_button setTintColor:UIColor.whiteColor];
        _button.center = CGPointMake(self.view.center.x, 150);
        [_button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_button];
    }
    return _button;
}

响应button的点击事件,当button被点击时,创建一个json字符串,传递给html页面,这样就可以完成echarts图形的绘制

//OC中调用js代码
-(void)buttonClicked:(UIButton *)button{
    //准备数据源
    NSArray *values = @[@1212,@2332,@1919];
    NSArray *nameValues = @[@"A",@"B",@"C"];

    NSMutableArray *arrayM = [NSMutableArray array];
    for (int i=0; i<values.count; i++) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setValue:values[i] forKey:@"value"];
        [dict setValue:nameValues[i] forKey:@"name"];
        [arrayM addObject:dict];
    }
    
    NSDictionary *optionDict = @{
        @"series" : @{
                @"type" : @"pie",
                @"data" : arrayM
        }
    };
    
   //字典数据转化为json字符串,并调用html中js的函数test1(params)
    NSString *ocToJs = [NSString stringWithFormat:@"test1(%@)",[self dictToJson:optionDict]];
   //执行json字符串,这里会进行与html中js的进行交互
    [self.webView evaluateJavaScript:ocToJs completionHandler:^(id _Nullable name, NSError * _Nullable error) {
        NSLog(@"方法调用完成回调");
    }];
}

-(NSString *)dictToJson:(NSDictionary *)dict{
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonStr;
}

3. 完整代码

//
//  ViewController.m
//  08-wkwebView
//
//  Created by EVAN YANG on 2020/5/11.
//  Copyright © 2020 EVAN YANG. All rights reserved.
//

#import "ViewController.h"
#import <WebKit/WebKit.h>

@interface ViewController ()<WKUIDelegate,WKNavigationDelegate>

@property(nonatomic,strong)WKWebView *webView;
@property(nonatomic,strong) UIButton *button;

@end


@implementation ViewController

- (UIButton *)button{
    if (_button == nil) {
        _button = [[UIButton alloc]initWithFrame:CGRectMake(30,30,200,40)];
        _button.backgroundColor = [UIColor redColor];
        [_button setTitle:@"显示简单的扇形图" forState:UIControlStateNormal];
        [_button setTintColor:UIColor.whiteColor];
        _button.center = CGPointMake(self.view.center.x, 150);
        [_button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_button];
    }
    return _button;
}

- (WKWebView *)webView{
    if (_webView == nil) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0,0,200,200) configuration:config];
        _webView.backgroundColor = UIColor.lightGrayColor;
        _webView.allowsBackForwardNavigationGestures = YES;
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        _webView.center = self.view.center;
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
        NSString *htmlStr = [[NSString alloc]initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        [_webView loadHTMLString:htmlStr baseURL:[[NSBundle mainBundle] bundleURL]];
        
        [self.view addSubview:_webView];
    }
    return _webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self webView];
    [self button];
}

//OC中调用js代码
-(void)buttonClicked:(UIButton *)button{
    NSArray *values = @[@1212,@2332,@1919];
    NSArray *nameValues = @[@"A",@"B",@"C"];
    NSMutableArray *arrayM = [NSMutableArray array];
    for (int i=0; i<values.count; i++) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setValue:values[i] forKey:@"value"];
        [dict setValue:nameValues[i] forKey:@"name"];
        [arrayM addObject:dict];
    }
    
    NSDictionary *optionDict = @{
        @"series" : @{
                @"type" : @"pie",
                @"data" : arrayM
        }
    };
    
    NSString *ocToJs = [NSString stringWithFormat:@"test1(%@)",[self dictToJson:optionDict]];
    [self.webView evaluateJavaScript:ocToJs completionHandler:^(id _Nullable name, NSError * _Nullable error) {
        NSLog(@"方法调用完成回调");
    }];
}

//字典转json字符串
-(NSString *)dictToJson:(NSDictionary *)dict{
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonStr;
}

//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    NSLog(@"didStartProvisionalNavigation");
}

//正在加载
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    NSLog(@"didCommitNavigation");
}

//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSLog(@"didFinishNavigation");
    
//    NSString *ocToJs = @"test1()";
//    [self.webView evaluateJavaScript:ocToJs completionHandler:^(id _Nullable name, NSError * _Nullable error) {
//        NSLog(@"方法调用完成回调");
//    }];
}

@end


相关文章

网友评论

    本文标题:iOS-Echarts的简单应用

    本文链接:https://www.haomeiwen.com/subject/fecpnhtx.html