In development projects, there is a need to display mathematical formulas, such as the following

There are three ways to achieve the above display:

Use pictures

The mathematical formula is generated on the server side, and the front end uses the picture to show the mathematical formula.

In this way, the front end is difficult to typeset, difficult to control the scale of the image, and low flexibility.

WebView loads mathematical formula engine — KaTeX

There is now a very mature typesetting system, LaTeX, which supports the use of text to express complex mathematical formulas, tables, and so on. For purely mathematical formulas, you can use KaTeX, a subset of LaTeX, which is a lightweight mathematical formula engine that supports HTML.

We can create a WebView when we need to display the math formula and introduce KaTeX to render the math formula.

There are several problems with this approach:

  1. The WebView loads mathematical formulas very slowly.
  2. If you need to load mathematical formulas in the TableView Cell, there may be a page in need of multiple WebViews, will further meet the speed of page refresh. Secondly, TableView can not automatically infer the height of the WebView, so it is difficult to control the height of the Cell.

IosMath + YYText

IosMath is a framework dedicated to displaying math formulas, but it does not support displaying other text along with math formulas. So we can only extract the math from a piece of text and throw it into iosMath, and the rest of the content needs to be displayed by other controls.

So we also need to use YYText to use the MTMathUILabel in the iosMath framework to display the math formula as a section of AttachmentString to concatenate it with other text.

In addition, when the mathematical formula is too long and a page is not fully displayed, it needs to scroll left and right to facilitate users to view the mathematical formula. So the YYLabel used to present the information also needs to be placed in a UIScrollView.

For details, see Github.

Project Screenshot 1 Project Screenshot 2

reference

Liao Xuefeng — Using KaTeX to render mathematical formulas