SwiftUI: How to build text with subScript and super Script?
Xcode 12 — iOS14
1 min readMay 3, 2021
In this tutorial, We will be implementing logic to make text with Subscripts and Superscripts.
To implement subscript/superscripts first we need to define a logic to understand what part of text will be carried as sub/super scripts.
1. Any text in ^{} will be treated as superscript.
e.g. => X^{2} -> X²2. Any text in _{} will be treated as subscript.
e.g. => H_{2} => H₂
We are going to use following Text property:
var text = Text("pre") + Text("post")//Also
text = text + Text("more text")Text("X").font(.callout) + Text(2).font(.caption).baselineOffset(6.0)Output => X²
Logic to implement:
1. Iterate throw String for find first ^ or _
2. split string add first part as it is.
3. Check if this string followed by {<data>}
4. if yes set the baseline for <data> and ignore ^_{}
5. redo the step 1-4 for second part of string after reducing ^_{<data>}