user216661
user216661

Reputation: 323

Dynamically change iphone/iPad text to a custom font

I want to create an app that uses the user's custom font, therefore I want to my app to load the ttf file at run time. I am familiar with adding custom font via the UIAppFonts key as discussed in Adding custom font on iphone. Presumably I wouldn't be successful creating a placeholder custom font that could be swapped out by my app, if provided a user-created custom version?

Upvotes: 3

Views: 699

Answers (1)

WalterF
WalterF

Reputation: 1363

The font file I used was this: http://www.webpagepublicity.com/free-fonts/a/Almagro%20Regular.ttf

And I did it using this code:

 CGDataProviderRef fontDataProvider = CGDataProviderCreateWithFilename([fontFilepath UTF8String]);

 // Create the font with the data provider, then release the data provider.
CGFontRef customFont =  CGFontCreateWithDataProvider(fontDataProvider);
CGDataProviderRelease(fontDataProvider);

CFErrorRef error = nil;
CTFontManagerRegisterGraphicsFont(customFont, &error);

CGFontRelease(customFont);

if (error != nil)
{
    NSError* err = (__bridge NSError*)error;
    NSLog(@"error code %d desc: %@",err.code, [err description]);
}

UIFont* f = [UIFont fontWithName:@"Almagro" size:14.0];

There are some gotcha's though. You need to know the font name since it might differ slightly from the file name. In my example, the file name was "Almagro Regular.ttf" but the font name was just "Almagro". On another forum someone said that you need to be careful about fonts with spaces in their names because a font like "Sans Serif" would be registered as "SansSerif" for UIFont fontWithName:size:

Let me know if it works.

Upvotes: 3

Related Questions