-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKatexMathView.swift
More file actions
73 lines (53 loc) · 2.21 KB
/
KatexMathView.swift
File metadata and controls
73 lines (53 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//
// KatexMathView.swift
//
// Created by rajeswari on 5/7/19.
// Copyright © 2019 Rajeswari Ratala. All rights reserved.
//
import UIKit
import WebKit
class KatexMathView: WKWebView {
func loadLatex(_ content: String ) {
guard let path = Bundle.main.path(forResource: "katex/index", ofType: "html") else {
fatalError()
}
self.configuration.preferences.javaScriptEnabled = true
self.scrollView.isScrollEnabled = false
self.scrollView.bounces = false
self.navigationDelegate = self
self.isOpaque = false
self.backgroundColor = UIColor.clear
self.scrollView.backgroundColor = UIColor.clear
let htmlContent = getHtml(content, path)
self.loadHTMLString(htmlContent, baseURL: URL(fileURLWithPath: path))
}
func getHtml(_ htmlContent: String, _ path: String) -> String {
var htmlString = try! String(contentsOfFile: path, encoding: .utf8)
var content = htmlContent
let delimitter = "$"
let startTexTag = "<span class=\"tex\">"
let endTexTag = "</span>"
var first = true
while content.contains(delimitter) {
let tag: String = first ? startTexTag : endTexTag
if let range = content.range(of: delimitter) {
content = content.replacingOccurrences(of: delimitter, with: tag, options: NSString.CompareOptions.literal, range: range)
}
first = !first
}
htmlString = htmlString.replacingOccurrences(of: "$LATEX$", with: content)
return htmlString
}
}
extension KatexMathView : WKNavigationDelegate {
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
if complete != nil {
self.evaluateJavaScript("document.body.scrollHeight", completionHandler: { (height, error) in
self.frame.size.height = height as! CGFloat
self.layoutIfNeeded()
})
}
})
}
}