Swift UILabel Extension for setting attributedText with specified character indices in subscript

Alexandros Baramilis
1 min readApr 11, 2019

--

Using the above extension you can set the attributedText of a UILabel with an attributed string that will display all the characters at the specified indices in the given string in subscript.

It takes the current font of the UILabel and sets the subscript font as 0.7 times the size of the current font.

It also offsets the digits vertically by an amount equal to 0.3 times the size of the current font.

This ensures that the subscripts look good for any font size.

Example:

label.setAttributedTextWithSubscripts(text: “H2O”, indicesOfSubscripts: [1])

Will display as:

H₂O

Bonus: If you want to display all the numbers in a string in subscript, you can combine the above extension with another extension I made that finds the indices of all the numbers in a string.

--

--