Every new iOS design I have to implement uses custom fonts. A few years back this would have been impossible but luckily since iOS4 it’s been reasonably simple to add your own fonts to iOS Apps. The process is as follows:
- Add the font (*.ttf or *.otf) to the project
- Make sure it is added to ‘Copy Bundle Resources’ under Build Phases in the project target
- Add a key to your info.plist file called UIAppFonts, or it’s long name which is ‘Fonts provided by application’
- Make sure this an array (it is by default in Xcode 4.3)
- For each of your font files add the full filename including the extension as a new string key inside the UIAppFonts array.
Your custom fonts should now be successfully added to the project. There are two ways to use them. First for iOS4 and iOS5 you can just assign the following to the font variable on an object:
[UIFont fontWithName:@"CustomFontName" size:14.0]
The CustomFontName needs to be the name of the font from Font Book, not the filename! (UPDATE: As it turns out this isn’t always the case, check out my separate post about this)
Alternatively if you are only targeting iOS5 you can use the new Appearance proxy. The following code will set all the UILabel fonts to be your custom font.:
[[UILabel appearance] setFont:[UIFont fontWithName:@"CustomFontName" size:14.0]];
You can also use the custom font in Interface Builder if you install the font onto your mac using Font Book.
Most of the custom fonts i’ve used usually have some issue with their vertical alignment. Either they sit too low or too high when compared to the default fonts. This poses a lot of problems and makes it quite difficult to get things aligned properly. The cause of this is that your custom font has an ascender and descender settings which are not being rendered properly by iOS.
Let me explain quickly what these two are before going any further. The ascender is essentially the whitespace at the top of a font and the descender is the whitespace at the bottom of a font, the two combined space the font out correctly in relation to screen elements and other fonts. I have no idea why iOS doesn’t seem to like them but I can hopefully give you a solution.
To edit these in the font you will need to download the Apple Font Tool Suite. Once you’ve installed this you need to open Terminal and navigate to the directory that contains your font. After that enter the following command:
ftxdumperfuser -t hhea -A d font.ttf
This will create a file called font.hhea.xml, open this new file into a text editor and adjust the values for ascender and descender. Generally if you font sits too low you want to decrease ascender and increase descender. After editing and saving enter the following command into terminal to reconstruct your Font file:
ftxdumperfuser -t hhea -A f font.ttf
You can now use the font.ttf file in your application. If the font still isn’t right just repeat the above procedure until you are happy.