我是Swift编程新手,希望用SwiftUI创建一个应用程序。这就是我希望实现的目标:
也就是说,文本字段具有针对LaTeX
的实时语法突出显示,然后其内容由mathjax
呈现并显示在web视图中。
我在这个网站和GitHub上做了一些搜索,只发现相关的代码大多是Objective-C或Swift 4.x (如this)的,没有一个是用SwiftUI做的接口。然而,在我的研究过程中,我发现了一种可能可行的方法。似乎使用JavaScriptCore框架可以使用highlight.js来突出显示语法(就像Highlightr在那里做的那样,但它的代码非常复杂)。我对这种方法深信不疑,因为如果可以使用highlight.js
来实现代码突出显示,那么以类似的方式,就应该能够使用其他JavaScripts (如mathjax.js
)来实现其他功能。
不幸的是,由于我是Swift和SwiftUI的新手,我不知道从哪里开始。有没有人能给我一些提示?(欢迎任何帮助,不一定要使用JavaScriptCore
)
发布于 2020-12-01 12:33:26
这里有一个可能的解决方案,它使用了一个很棒的框架,RichTextView
import RichTextView
struct ContentView : View {
@State var string : String = "In physics, the mass-energy equivalence is stated by the equation [math]$E=mc^2$[/math], discovered in 1905 by Albert Einstein."
var body : some View {
TextField("Test", text: $string)
.padding(.vertical, 32)
.border(Color.red)
TextView(string: $string)
.padding(.horizontal, 16)
}
}
struct TextView : UIViewRepresentable {
@Binding var string : String
func makeUIView(context: Context) -> RichTextView {
let richTextView = RichTextView(
input: string,
latexParser: LatexParser(),
font: UIFont.systemFont(ofSize: UIFont.systemFontSize),
textColor: UIColor.black,
frame: CGRect.zero,
completion: nil
)
return richTextView
}
func updateUIView(_ uiView: RichTextView, context: Context) {
uiView.update(
input: string,
latexParser: LatexParser(),
font: UIFont.systemFont(ofSize: UIFont.systemFontSize),
textColor: UIColor.black,
completion: nil
)
}
}
你总是必须从数学开始,以/math but结束可以使用默认的Latex。有关其文档的更多信息。
发布于 2020-12-03 13:37:46
这是我目前的解决方案,它使用CodeViewer包来突出显示代码,使用mathjax.js
来渲染数学。
import SwiftUI
import CodeViewer
struct LaTeXView: View {
@State private var placeholderString: String = "Insert here"
@State private var inputText: String = ""
var body: some View {
VStack {
//MARK: Code editor
CodeViewer(
content: $inputText,
mode: .latex,
darkTheme: .solarized_dark,
lightTheme: .solarized_light,
isReadOnly: false,
fontSize: 50
)
//MARK: for rendering math
HTMLStringView(htmlContent: """
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>MathJax example</title>
<script>MathJax = {
tex:{
inlineMath: [['$', '$'], ['\\(', '\\)']],
tags: 'ams'
},
svg:{
fontCache: 'global'
}
};
</script>
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script id="MathJax-script" async
src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">
</script>
</head>
<body>
<p>
\(inputText.replacingOccurrences(of: "\n\n", with: "<br>"))
</p>
</body>
</html>
"""
)
}
}
}
struct LaTeXView_Previews: PreviewProvider {
static var previews: some View {
LaTeXView()
}
}
结果如下所示:
https://stackoverflow.com/questions/65090289
复制相似问题