swiftui - 如何在 SwiftUI 中使用 LaTeX 创建数学公式文本视图?
问题描述
我是 Swift 编程新手,希望使用 SwiftUI 创建一个应用程序。这是我希望达到的目标:
即,具有实时语法高亮显示的文本字段,LaTeX
然后其内容由 Web 视图呈现mathjax
并显示在 Web 视图中。
我在这个网站和 GitHub 上做了一些搜索,才发现相关代码大多在 Objective-C 或 Swift 4.x 中(例如this),并且没有一个是用 SwiftUI 制作的接口。然而,在我的研究中,我发现了一种可能有效的方法。似乎使用JavaScriptCore框架可以使用highlight.js来进行语法高亮(就像Highlightr在那里所做的那样,但它的代码非常复杂)。我对这种方法深信不疑,因为如果可以使用highlight.js
来实现代码突出显示,那么应该能够以类似的方式使用其他 JavaScriptmathjax.js
来实现其他功能。
不幸的是,由于我是 Swift 和 SwiftUI 的新手,我不知道从哪里开始。谁能给我一些提示?(欢迎任何帮助,不一定使用JavaScriptCore
)
解决方案
这是使用出色框架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] 开头并以 [/math] 结尾,但可以使用默认的 Latex。有关其文档的更多信息。
推荐阅读
- python - Robot-Framework:如何从关键字中获取列表并验证项目
- javascript - 多个模式听同一个按键,我如何处理优先级?
- python - .append() 返回无
- reactjs - 在 react onClick 上激活 2 个不同的调用
- netlogo - 计算邻居之间海龟的步数
- excel - 用于检查值是否存在的 Excel 公式,否则不显示任何内容 - 也使用条件格式
- shopify - 如何在 shopify 中创建自定义 webhook
- python - Python Pandas 隔夜数据分组
- jitsi - Jitsi 配置大厅
- javascript - 不使用 HTML 的打字效果 JS