iOS-Echarts的簡(jiǎn)單應(yīng)用

1. 效果圖

用戶點(diǎn)擊紅色按鈕匠童,即顯示扇形圖


oc調(diào)用echarts.png

2. 設(shè)計(jì)思路

2.1 創(chuàng)建一個(gè)index.html,引入echarts庫文件。編寫js測(cè)試函數(shù)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)
        {
            // 基于準(zhǔn)備好的dom撰茎,初始化echarts實(shí)例
            var myChart = echarts.init(document.getElementById('main'));
            // 使用剛指定的配置項(xiàng)和數(shù)據(jù)顯示圖表。
            myChart.setOption(option);
        }
    </script>
</body>
</html>

2.2 在OC界面打洼,需要使用wkwebView去訪問html資源龄糊,并和步驟1創(chuàng)建的js函數(shù)進(jìn)行交互
懶加載一個(gè)wkwebView對(duì)象

- (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;
}

懶加載一個(gè)button

- (UIButton *)button{
    if (_button == nil) {
        _button = [[UIButton alloc]initWithFrame:CGRectMake(30,30,200,40)];
        _button.backgroundColor = [UIColor redColor];
        [_button setTitle:@"顯示簡(jiǎn)單的扇形圖" 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;
}

響應(yīng)button的點(diǎn)擊事件逆粹,當(dāng)button被點(diǎn)擊時(shí),創(chuàng)建一個(gè)json字符串炫惩,傳遞給html頁面僻弹,這樣就可以完成echarts圖形的繪制

//OC中調(diào)用js代碼
-(void)buttonClicked:(UIButton *)button{
    //準(zhǔn)備數(shù)據(jù)源
    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
        }
    };
    
   //字典數(shù)據(jù)轉(zhuǎn)化為json字符串,并調(diào)用html中js的函數(shù)test1(params)
    NSString *ocToJs = [NSString stringWithFormat:@"test1(%@)",[self dictToJson:optionDict]];
   //執(zhí)行json字符串他嚷,這里會(huì)進(jìn)行與html中js的進(jìn)行交互
    [self.webView evaluateJavaScript:ocToJs completionHandler:^(id _Nullable name, NSError * _Nullable error) {
        NSLog(@"方法調(diào)用完成回調(diào)");
    }];
}

-(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:@"顯示簡(jiǎn)單的扇形圖" 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中調(diào)用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(@"方法調(diào)用完成回調(diào)");
    }];
}

//字典轉(zhuǎn)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(@"方法調(diào)用完成回調(diào)");
//    }];
}

@end


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末蹋绽,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子筋蓖,更是在濱河造成了極大的恐慌卸耘,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,546評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件粘咖,死亡現(xiàn)場(chǎng)離奇詭異蚣抗,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)瓮下,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門翰铡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人唱捣,你說我怎么就攤上這事两蟀。” “怎么了震缭?”我有些...
    開封第一講書人閱讀 164,911評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵赂毯,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我拣宰,道長(zhǎng)党涕,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,737評(píng)論 1 294
  • 正文 為了忘掉前任巡社,我火速辦了婚禮膛堤,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘晌该。我一直安慰自己肥荔,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,753評(píng)論 6 392
  • 文/花漫 我一把揭開白布朝群。 她就那樣靜靜地躺著燕耿,像睡著了一般。 火紅的嫁衣襯著肌膚如雪姜胖。 梳的紋絲不亂的頭發(fā)上誉帅,一...
    開封第一講書人閱讀 51,598評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼蚜锨。 笑死档插,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的亚再。 我是一名探鬼主播郭膛,決...
    沈念sama閱讀 40,338評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼氛悬!你這毒婦竟也來了饲鄙?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,249評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤圆雁,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后帆谍,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體伪朽,經(jīng)...
    沈念sama閱讀 45,696評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,888評(píng)論 3 336
  • 正文 我和宋清朗相戀三年汛蝙,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了烈涮。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,013評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡窖剑,死狀恐怖坚洽,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情西土,我是刑警寧澤讶舰,帶...
    沈念sama閱讀 35,731評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站需了,受9級(jí)特大地震影響跳昼,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜肋乍,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,348評(píng)論 3 330
  • 文/蒙蒙 一鹅颊、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧墓造,春花似錦堪伍、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至谱煤,卻和暖如春摊求,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評(píng)論 1 270
  • 我被黑心中介騙來泰國(guó)打工室叉, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留睹栖,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,203評(píng)論 3 370
  • 正文 我出身青樓茧痕,卻偏偏與公主長(zhǎng)得像野来,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子踪旷,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,960評(píng)論 2 355