HighCharts - iOS

365 阅读2分钟

Api:

api.highcharts.com/ios/highcha…

iOS demo:

www.highcharts.com/demo/ios

使用教程:

www.highcharts.com.cn/docs

使用CSS:

www.highcharts.com/docs/chart-…

highCharts 使用的是SVG来实现的,所以CSS需要使用SVG可以使用的语法 并且如果不是全部自定义的话,只能使用HighCharts提供的CSS名称

svg学习链接:www.w3.org/TR/SVG/path…

注入代码:

1. 获取当前的chartview中的webview,并设置delegate

self.chartView = HIChartView(frame: CGRect(x: 5.0, y: 5.0, width: self.view.frame.size.width - 20, height: 340.0))

let web = **self**.chartView!.subviews[0] **as**? WKWebView

web?.navigationDelegate = **self**

2. 在回调中注入

注:(其中的css名称要符合上面的HighCharts提供的名称和svg语法)

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

        insertCSSString(into: webView)

}

func insertCSSString(into webView: WKWebView) {

        let cssString = ".highcharts-color-0 { fill: #f00 }"

        let jsString = "var style = document.createElement('style'); style.innerHTML = '\(cssString)'; document.head.appendChild(style);"

        webView.evaluateJavaScript(jsString)

    }

添加自定义样式

在formatter中写入JS方法

tooltip.formatter = HIFunction(jsFunction: "function() { return '...'; }")

添加自定义方法:

HIFunction和HIEvents将js代码包裹注入并注入

HIFunction 示例

Highcharts iOS 支持点击事件回调函数与原生程序绑定(即可以在点击事件里执行 iOS 原生行为,也可以添加web行为)。下面示例展示了通过原生 alert 来显示当前点击的点的坐标。

首先,您需要为您的系列类型创建一个 plotOptions 对象

HIPlotOptions *plotOptions = [[HIPlotOptions alloc] init];
plotOptions.series = [[HISeries alloc] init];

现在,您可以使用点事件并添加单击关闭,如下所示:

plotOptions.series.point = [[HIPoint alloc] init];
plotOptions.series.point.events = [[HIEvents alloc] init];

HIClosure closure = ^(HIChartContext *context) {
    NSString *alertMessage = [NSString stringWithFormat:@"Category: %@, value: %@", [context getProperty:@"this.category"], [context getProperty:@"this.y"]];

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:alertMessage preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {}];
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
};

plotOptions.series.point.events.click = [[HIFunction alloc] initWithClosure:closure properties:@[@"this.category", @"this.y"]];

向您在上面代码片段中看到的 一样,第一个参数 HIFunction 实际上是一个闭包。第二个参数是图表元素的简单字符串数组。我们需要将它们放在这里让扩展包在 HIFunction 实例化期间为我们提取它们。有了这个,我们可以通过 getProperty: 方法引用这些元素对应的值。您可以从此图表提取任何数据。根据实际的需要,您可以运行一些代码从图表中提取数据,将字符串返回给图表(例如:在 HITooltip 格式化中),甚至将纯 Javascript 函数以 String 的格式放在构造函数中。有关的更多信息,请查看 API 文档

动态改变行为:

可以在原本的行为中加上新的行为,如在显示tooltip的时候增加显示一个小球 www.highcharts.com/docs/extend…