Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a SwiftUI way of making text superscript or subscript?

Tags:

swiftui

I know an offset can be applied like Text("TM").offset(x:0 y:7) but is there a different or better way to create a bit of super or subscript text in SwiftUI?

like image 636
R. J. Avatar asked Jan 14 '20 22:01

R. J.


People also ask

How do I use subscript and superscript in Swift?

Create a NSMutableAttributedString with the full string and default font. Add an attribute to the characters you want to change ( NSRange ), with the smaller/subscript UIFont , and the NSBaselineOffsetAttributeName value is the amount you want to offset it vertically. Assign it to your UILabel.

How do you make text superscript and subscript?

Keyboard shortcuts: Apply superscript or subscript Select the character that you want to format. For superscript, press Ctrl, Shift, and the Plus sign (+) at the same time. For subscript, press Ctrl and the Equal sign (=) at the same time.

How do I type a superscript in Xcode?

Pressing Cmd + Ctrl + Space will open a special characters menu. Check if the "Digits — All" category is in the left-hand column. If it isn't, click the gear icon, then select this category — add it to the list.

How will you display text as a superscript?

The <sup> tag defines superscript text. Superscript text appears half a character above the normal line, and is sometimes rendered in a smaller font. Superscript text can be used for footnotes, like WWW. Tip: Use the <sub> tag to define subscript text.


1 Answers

Here's a generic way using .baselineOffset:

          Text("Company")
            .font(.callout)
          + Text("TM")
              .font(.system(size: 8.0))
              .baselineOffset(6.0)

I'm sure there's a way to get the correct offset dynamically using CTFont, but I think it may be a pain. A sloppy way would be to wrap the Text View(s)? in a GeometryReader, and use the height to try and position it so it looks good.

You can also use Unicode for some symbols (like ™):

Text("Company\u{2122}")
like image 167
Austin Avatar answered Nov 07 '22 23:11

Austin