Adoption Curve Dot Net

Adding Non-standard Fonts to iOS5 Apps

| Comments

iOS6 ships with a decent variety of fonts, but every so often your app design will dictate using something other than the built-in ones. Adding custom fonts is pretty straight-forward:

  1. Add the .TTF or .OTF font file to the project as a resource (I stick them in a group so I can find them alongside all the other project assets).
  2. In the app’s pList file, add a new row and select the “Fonts provided by application” name for it.  This will create an array.
  3. Add a new item for each of the font files you’ve added, and enter the full name (with extension) of the file.

This then adds the font as a resource for any code using a UIFont class method.   You need to use it with something along the lines of:

[myLabel setFont:[UIFont fontWithName:@"theFontName" size:25]];`

The font name string isn’t necessarily immediately obvious from the font file itself, so here’s a snippet that will dump all the font names in the app.  UIFonts are collected into families, and each family has one or more fonts with a unique name:

NSArray *fontNames = [UIFont familyNames];
for (NSString *familyName in fontNames) {
    NSLog(@"Font family name = %@", familyName);
    NSArray *names = [UIFont fontNamesForFamilyName:familyName];
    NSLog(@"Font names = %@", names);
}

So for example, the Palatino family has four fonts named:

   "Palatino-Roman",
   "Palatino-Bold",
   "Palatino-BoldItalic",
   "Palatino-Italic"

If you wanted to use Palatino Bold Italic as the font for a UILabel, you’d set that using

    [myLabel setFont:[UIFont fontWithName:@"Palatino-BoldItalic" size:25]];

Listing the fonts is the kind of thing you’ll probably only need to do once in the lifecycle of a project, but it’s a useful list to have to save some time during development.  Misspell the font name and UIKit will substitute the bog-standard Helvetica – which isn’t always immediately obvious when you’re coding.

Comments