UIAppFonts – custom fonts with the iPhone/iPad 3.2 SDK

Recently I had some problems getting custom fonts working with the new iPhone/iPad 3.2 SDK using Interface Builder. In the new SDK it’s supposed to be really easy in theory, but there is currently a bug with Interface Builder/xCode that ruins it. I’ll share my workaround how to get it to work and if you have better ideas – I would be really grateful to hear abut them.

First, the way it’s supposed to work:

  • Add the custom font to your Xcode project
  • Add the name of the *.ttf (I’ve also had success with *.ttc) file to your Info.plist under UIAppFonts (Array)
  • Set the font property of any UILabel to match your newly added font name (you can discover the actual font names by iterating over [UIFont familyNames] and [UIFont fontNamesForFamily])

When done manually in code it should look something like this:

// MyViewController.h
@interface MyViewController : UIViewController {
    UILabel *myLabel;
}

// connect with IB
@property(nonatomic, retain) IBOutlet UILabel *myLabel;

@end

// MyViewController.m
@implementation MyViewController

@synthesize myLabel;

- (void) viewDidLoad {
    [myLabel setFont: [UIFont fontWithName: @"Quake" size: myLabel.font.pointSize]];
}

@end

While the above does work, connecting every UILabel manually to an IBOutlet and then implementing the same thing over and over again for each label seemed like a bad idea. My workaround was to define a custom UILabel subclass for each different custom font I needed to use (fortunately only 4) and then use those subclasses instead in Interface Builder:

// LabelQuake.h
#import <uikit /UIKit.h>
@interface LabelQuake : UILabel {

}

@end

// LabelQuake.m
#import "LabelQuake.h"
@implementation LabelQuake

- (id)initWithCoder:(NSCoder *)decoder {
   
    if (self = [super initWithCoder: decoder]) {
        [self setFont: [UIFont fontWithName: @"Quake" size: self.font.pointSize]];
    }
   
    return self;
}


@end

This way my controllers don’t have to know about every label and it’s SEMI-DRY ;)

!PS: people not using IB, but building their UI in code should just ignore the above, everything should just work.
!PS: I’ll update this post when the bug gets updated/closed in Radar with more info.

Leave a Reply

Work with us