Skip to main content


Showing posts from December, 2013

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: draw the string directly inside the drawRect method of a UIView use a CATextLayer  use a UILabel (iOS 6 onwards) 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 = [[CATextLay

NSMutableArray, indexOfObject:, NSNull and NSNotFound (Xcode for iOS)

Creating an array with empty objects NSMutableArray is a useful class for ordering objects and keeping them in order. So let's suppose we have a set number of items, for example pages in a book. We might want to place each view, or view controller, that represents a page in the book at the correct place in the array, but not necessarily want all of the pages to be held in the array at one time. So first of all we need an array of empty objects. And let's say we'd like it to be 20 objects long. NSMutableArray *pagesArray = [[NSMutableArray alloc] init]; int i = 0; for (i < 20)  { [pagesArray addObject:[NSNull null]] i++; } Replacing empty objects with real ones Now we have an array into which we can insert our page objects at their correct places. [pagesArray replaceObjectAtIndex:10 withObject:page11] Of course in real use we would've instantiated whatever it is our page11 object is, but for now it's the array we're interested in. Knowin