iOS--3分钟教会你用mathjax显示数学公式
iOS–3分钟教会你用mathjax显示数学公式
最近开发数学教程,需要显示数学公式和图形,找了很多资料,找到2种方法,1、服务器返回Latex的字符串 我在客户端用webView来展示与交互,但是有一些标签不认,解释不全。2、用封装好的MathJax库显示数学公式和图形,也是用wkwebView展示,返回高度
我们先看gif效果图!
知识点:涉及OC与JS的交互,双方传值,互相调取
- 引入MathJaxbai库
导入
#import <JavaScriptCore/JavaScriptCore.h>
#import <WebKit/WebKit.h>
实现wkWebView以及相关配置(WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate)代理
2、OC传参给js 定义一个相同的参数名htmlCall,js就可以接受到参数,注意一定要放在-(void)webView:(WKWebView )webView didFinishNavigation:(WKNavigation )navigation{}代理中
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
NSDictionary *aaa@qq.com{@"answers" :@"$18\\times 901=16218$.", @"analysis":@"分析加法竖式,可知第一个加数为18,第二个加数为162;<br\/>根据这两个加数的倍数关系:$162=18\\times 9$,可知第二个因数的百位是个位的9倍,那么第二个因数是901;<br\/>所以,乘法算式为$18\\times 901=16218$.",@"subjects":@"请将下面的竖式补充完整.<img src='https:\/\/vsrc.vistateach.com\/hw\/m\/q\/demo3.png'><\/img>",@"question_finish" :@1};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:j options:NSJSONWritingPrettyPrinted error:nil];
NSString * str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *js = [NSString stringWithFormat:@"htmlCall(%@)",str];
[webView evaluateJavaScript:js completionHandler:nil];
}
H5中的JS 前端自行处理接收到的含Latex的字符串,去展示
var htmlCall = function(json_arr){
<!-- var json_arr = JSON.parse(str)-->
document.getElementById('subjects').innerHTML=json_arr.subjects;
if(json_arr.question_finish == 1){
document.getElementById('answers').innerHTML=json_arr.answers;
document.getElementById('analysis').innerHTML=json_arr.analysis;
document.getElementById('answers_par').style.display = 'block';
document.getElementById('analysis_par').style.display = 'block';
}
JS返回高度给OC,首先注入JS[config.userContentController addScriptMessageHandler:self name:@”htmlCallBack”];其次,OC接受参数,设置wkWebView高度,最好在代理-(void)userContentController:(WKUserContentController )userContentController didReceiveScriptMessage:(WKScriptMessage )message{}接收,最后,js中设置window.webkit.messageHandlers.htmlCallBack.postMessage(height)
//注入JS
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
config.preferences = [[WKPreferences alloc]init];
config.preferences.javaScriptEnabled = YES;
config.userContentController = [[WKUserContentController alloc]init];
[config.userContentController addScriptMessageHandler:self name:@"htmlCallBack"];
//OC接收参数
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
NSNumber *msgStr = message.body;
NSLog(@"JS交互参数:%@", msgStr);
if ([message.name isEqualToString:@"htmlCallBack"]) {
//处理高度
}
}
注意引入MathJax库的时候
加载时
NSString *str = [[NSBundle mainBundle] pathForResource:@"mathSubject" ofType:@"html" inDirectory:@"MathJax/test"];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:str]]];
demo下载
demo
欢迎斧正!
上一篇: Android与Js基本交互
下一篇: Base64--图片base64解码简说