How do I use subscript and superscript in Swift?

Most of the answers+examples are in ObjC, but this is how to do it in Swift.

let font:UIFont? = UIFont(name: "Helvetica", size:20)
let fontSuper:UIFont? = UIFont(name: "Helvetica", size:10)
let attString:NSMutableAttributedString = NSMutableAttributedString(string: "6.022*1023", attributes: [.font:font!])
attString.setAttributes([.font:fontSuper!,.baselineOffset:10], range: NSRange(location:8,length:2))
labelVarName.attributedText = attString

This gives me:

SuperScript Example

In a more detailed explanation:

  1. Get UIFont you want for both the default and superscript style, superscript must be smaller.
  2. Create a NSMutableAttributedString with the full string and default font.
  3. 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.
  4. Assign it to your UILabel

Hopefully this helps other Swift devs as I needed this as well.

Leave a Comment