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 *[email protected]{@"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 歡迎斧正!