Search code examples
objective-cnsstringnsattributedstring

How to make subscripts and superscripts using NSAttributedString?


I need to make subscripts for chemistry formulas (H2O, Na^2+, etc)?

Is this possible to do with NSAttributedString, or is there an alternative/easier way to make subscripts?


Solution

  • This is possible to do with NSAttributedString. The attribute constant you're looking for depends on your platform. For Mac OS X it is NSSuperscriptAttributeName and on iOS it is kCTSuperscriptAttributeName. Pass in a negative value for subscript.

    The only caveat is that UILabel on iOS can't draw NSAttributedStrings (yet, fingers crossed for iOS 6). You would need to draw the text using Core Text or find some third party replacement for UILabel that can draw an NSAttributedString.