首页 > 解决方案 > 如何在 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

标签: swiftui

解决方案


这是使用出色框架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。有关其文档的更多信息。


推荐阅读