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?
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.
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.
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.
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.
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}")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With