2016-02-27 70 views
0

我希望使用MathJax在Web視圖中顯示格式化的數學公式。我已經看到關於這個主題的各種討論,但他們主要是Objective-C(我正在使用Swift)。iOS的Swift語法Mathjax

到目前爲止,我已將「MathJax-master」文件夾拖放到我的Xcode項目中(我希望MathJax引擎存儲在本地,因此應用程序無法連接到互聯網)。我接下來要在Web視圖中顯示...也許:「Hello world,x = y^2」

我發現下面的教程,但(再次)我認爲這是在Objective-C,和我有麻煩翻譯成斯威夫特語法:http://new2objectivec.blogspot.com.au/2012/02/tutorial-how-to-setup-mathjax-locally.html

如果任何人都可以請點我到正確的斯威夫特語法,將非常感激。

回答

1

下面的代碼爲我工作:

//Function below concatenates an HTML file String, stores it locally, then calls it to display in a UIWebView using NSURLRequest with MathJax typesetting: 
func formatWebViewText(){ 

//Specify the text that will go in the HTML file: 
let htmlString: NSString = "<head><script type=\"text/x-mathjax-config\">MathJax.Hub.Config({tex2jax: {inlineMath: [ ['$','$'] ],},\"HTML-CSS\": { linebreaks: { automatic: true, width: \"container\" } } })</script><script src='" + 
    String(NSBundle.mainBundle().pathForResource("MathJax", ofType: "js", inDirectory: "MathJax-masterSlim")!) + //reference to local MathJax files 
    "?config=TeX-AMS-MML_HTMLorMML'></script></head>" + 
    "<body>" + questionMessage + "</body></html>" // "questionMessage" contains the text to be typeset/processed by MathJax 

//Give HTML file a name: 
let htmlFileName: NSString = "htmlTempFile.html" 

//Create a reference to the temporary directory that will store the HTML file: 
let tempDirectory: NSString = NSTemporaryDirectory() 

//Append reference temporary directory to include HTML file name: 
let htmlFilePath: NSString = tempDirectory.stringByAppendingPathComponent(htmlFileName as String) 

//Convert appended temporary directory NSString to an NSURL object: 
htmlUrl = NSURL(fileURLWithPath: htmlFilePath as String) 


//Below, HTML string is written to a file: 
do { try htmlString.writeToFile(htmlFilePath as String, atomically: true, encoding: NSUTF8StringEncoding) } 
catch { } 

//HTML file URL is fetched and displayed in UIWebView: 
QuestionWebView.loadRequest(NSURLRequest(URL: htmlUrl!)) 

} 
+0

如何在Webview中打印mathjax垂直中心 – srinadh

0

斯威夫特3

這裏是你的答案更新斯威夫特3和使用WKWebView(提供WebKit.framework,目前蘋果在一個UIWebView並推薦網頁視圖) :

guard let path = Bundle.main.path(forResource: "MathJax", ofType: "js", inDirectory: "MathJax-master") else { return } 
    let htmlString = "<head><script type=\"text/x-mathjax-config\">MathJax.Hub.Config({tex2jax: {inlineMath: [ ['$','$'] ],},\"HTML-CSS\": { linebreaks: { automatic: true, width: \"container\" } } })</script><script src='" + 
     path + //reference to local MathJax files 
     "?config=TeX-AMS-MML_HTMLorMML'></script></head>" + 
     "<body>" + enteredLatex + "</body></html>" 
    let filePath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("tempHTML.html") 
    do { 
     try htmlString.write(toFile: filePath.path, atomically: true, encoding: String.Encoding.utf8) 
    } catch { return } 
    webView.load(URLRequest(url: filePath))