How to show math symbols and equations in SwiftUI – LaTeX

In this tutorial, I will let you know how easily we can show math symbols in SwiftUI.

Showing simple mathematical symbols in SwiftUI is not a big deal.

Simple math symbols

We can do this easily like this:

SwiftUI can deal with the simple unicode math characters just like this:

Text("π ≈ 3.14159")
Text("√2 ≈ 1.414")

But you are here which means you are looking for something that will handle complex mathematical symbols.

Complex mathematical equations in SwiftUI ( LaTeX in SwiftUI)

In SwiftUI there is no built-in module or package that can handle LaTeX or complex mathematical equations.

But thank God there is Webkit.

We can do the same using Webkit package.

Webkit is not the package that will deal with LaTeX.

Webkit is just for rendering HTML. And we will use an external JavaScript library that can show complex mathematical equations in Web format.

LaTex in SwiftUI using Mathjax

Then we can easily show those equations through Webkit.

LaTeX in SwiftUI using Mathjax

See the below code:

import SwiftUI
import WebKit

struct LaTeXView: UIViewRepresentable {
    var latex: String

    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        return webView
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        let html = """
            <html>
            <style>
                body {
                    font-size: 100px; /* Adjust the size as needed */
                }
            </style>
            <head>
                <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>
                \\( \(latex) \\)
            </body>
            </html>
            """
        uiView.loadHTMLString(html, baseURL: nil)
    }
}

struct ContentView: View {
    var body: some View {
        LaTeXView(latex: "x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}")
    }
}

Output:

LaTeX in SwiftUI

As you can see, I can easily change the size and position of the output using HTML <style> tag.

If you face any challenges using the above method, do let me know in the comment section below. I will either come up with a better solution or update this post.

Leave a Reply

Your email address will not be published. Required fields are marked *