Drawing NSAttributedStrings with Superscripts and Subscripts (iOS/Xcode)

This is the briefest of brief posts dealing with Core Text and NSAttributedStrings in Xcode for iOS. First, let's create an attributed string and add a superscript attribute along with a font.

NSMutableAttributedString *stringOfText = [[NSMutableAttributedString alloc] initWithString:@"Hello World"];

[stringOfText addAttributes:@{(id < NSCopying >)kCTSuperscriptAttributeName:[NSNumber numberWithInt:1], NSFontAttributeName:[UIFont fontWithName:@"Georgia" size:20]} range:NSMakeRange(2,5)];

We now have a range of options. We could:
  1. draw the string directly inside the drawRect method of a UIView
  2. use a CATextLayer 
  3. use a UILabel (iOS 6 onwards)
  4. use a UITextView (iOS 7 onwards)
Explaining how to draw the string in the drawRect of a UIView is a post in its own right, so here I'll move swiftly on to look first at the CATextLayer option.

You'd add an attributed string to a CATextLayer like this:

CATextLayer *layerForText = [[CATextLayer alloc] init];
layerForText.string = stringOfText;
layerForText.foregroundColor = [UIColor blackColor].CGColor;
layerForText.frame = CGRectMake(100,100, self.view.frame.size.width,self.view.frame.size.height);
[self.view.layer addSublayer:layerForText];

Unfortunately, while you'll see the font has been applied, you won't see any letters made superscript. This is an issue for which there is no quick and easy solution, and so if you were determined to apply superscript you would have to look at the location of the line containing a superscript and work at a lower level than dealt with currently here (again another blogpost!).

The easier option is to apply a solution from iOS 6 or iOS 7. First, there is the UILabel for displaying the text.

UILabel *viewForDisplayingText = [[UILabel alloc] initWithFrame:CGRectMake(100,100, self.view.frame.size.width,self.view.frame.size.height)];
viewForDisplayingText.attributedText = stringOfText;
[self.view addSubview:viewForDisplayingText];

And second there is a UITextView (available from iOS 7 onwards):

UITextView *viewForDisplayingText = [[UITextView alloc] initWithFrame:CGRectMake(100,100, self.view.frame.size.width,self.view.frame.size.height)];
viewForDisplayingText.attributedText = stringOfText;
[self.view addSubview:viewForDisplayingText];

For more on UITextView see this blogpost and this one as well.


Endorse on Coderwall

Comments