Certain fonts not showing up? - ios

I have a list of font names in my app, which are all displayed in the font they represent. The following three do not work though:
ArialRoundedMTBold
ChalkboardSE-Bold
TrebuchetMS-Bold
Instead they display in the standard font.
Any ideas why these might not be showing up?

How to configure a custom font
To use a custom font (one not included in iOS) you have to edit your <appname>-Info.plist file and create a new UIAppFonts key with type array, where each element of the array is a String with the name of your font file. Example: VAGRoundedStd-Light.ttf. You also have to add the file to your project.
Note: When you type UIAppFonts and press enter, the key is converted to "Fonts provided by application".
However, when you use the font in Interface Builder (or with UIFont) you don't use the filename of the font, but the name that appears when you open the font in the application Font Book of your Mac. For the previous example it would be VAG Rounded Std Light.
OS X is more tolerant than iOS digesting TrueType formats, so on rare occasions you may find a font that works in OS X but not in iOS. If that happens, replace the font to see if at least you got the process right.
How to load a font programmatically
This solves the case where the font license requires you to distribute the font encrypted.
First step is to encrypt and decrypt the font with whatever algorithm you see fit.
Load the font as a NSData object and reverse the encryption.
Register the font programmatically.
This following recipe is from Loading iOS fonts dynamically by Marco Arment. It makes the fonts available in UIFont and UIWebView. The same code can be used to load fonts from the Internet.
NSData *inData = /* your decrypted font-file data */;
CFErrorRef error;
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)inData);
CGFontRef font = CGFontCreateWithDataProvider(provider);
if (! CTFontManagerRegisterGraphicsFont(font, &error)) {
CFStringRef errorDescription = CFErrorCopyDescription(error)
NSLog(#"Failed to load font: %#", errorDescription);
CFRelease(errorDescription);
}
CFRelease(font);
CFRelease(provider);
How to load more than two fonts of the same family
This is the case where iOS refuses to load more than two fonts from the same family.
Here is a code workaround from stackoverflow user Evadne Wu. Simply stick the following in your app delegate (note that it uses two frameworks):
#import <CoreText/CoreText.h>
#import <MobileCoreServices/MobileCoreServices.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
CTFontManagerRegisterFontsForURLs((__bridge CFArrayRef)((^{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *resourceURL = [[NSBundle mainBundle] resourceURL];
NSArray *resourceURLs = [fileManager contentsOfDirectoryAtURL:resourceURL includingPropertiesForKeys:nil options:0 error:nil];
return [resourceURLs filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSURL *url, NSDictionary *bindings) {
CFStringRef pathExtension = (__bridge CFStringRef)[url pathExtension];
NSArray *allIdentifiers = (__bridge_transfer NSArray *)UTTypeCreateAllIdentifiersForTag(kUTTagClassFilenameExtension, pathExtension, CFSTR("public.font"));
if (![allIdentifiers count]) {
return NO;
}
CFStringRef utType = (__bridge CFStringRef)[allIdentifiers lastObject];
return (!CFStringHasPrefix(utType, CFSTR("dyn.")) && UTTypeConformsTo(utType, CFSTR("public.font")));
}]];
})()), kCTFontManagerScopeProcess, nil);
return YES;
}
Available as gist. Commented in the author blog: Loading 2+ fonts on iOS from the same font family.
An alternative, more involved workaround from pixeldock.com:
If you add more than 2 font variants of the same font family (e.g.
“Normal”, “Bold” and “Extended”), only the last two font variants that
you added to the project will be usable.
If you see this happening, it is a limitation of your SDK version, and the only way out of it is editing the font family with a Font editor like Fontforge. Again, from pixeldock.com:
Open your Font in Fontforge
Goto ‘Element’ -> ‘Font Info’ and change the ‘Family Name’ field
Goto ‘Element’ -> ‘TTF Names’ and change the fields ‘Family’ and ‘Preferred Family’
Goto ‘File’ -> ‘Generate Fonts’ and save your edited font

Only a subset of Mac OS fonts are available in iOS. If you set a font that is not available, it will be displayed as the standard Helvetica.

I was using a Google font named Arvo. It had the following files:
Arvo-Regular.ttf
Arvo-Bold.ttf
Arvo-BoldItalic.ttf
Arvo-Italic.ttf
These names were added into my app's info.plist but for some reason, my app could only read the bold, bolditalic, and italic fonts. It couldn't read the regular font when i tried to load it. However, after printing out the font names, it came out that Arvo-Regular was recognized as Arvo in my app.

I had a similar issue with not finding Chalkduster - even though IB listed it as a font and it's listed as an IOS font. I discovered that the list of fonts on iPhone and iPad is not identical.
Chalkduster is available for iPad but not iPhone. Chalkboard is available on iPad 4.x but not 3.x. It is available on iPhone 3.x & 4.x.
More details here: http://www.whatsyourdigitaliq.com/2011/05/11/fonts-available-in-various-versions-of-ios/

Open Font Book application. If you installed the fonts yourself, go to user, look for the fonts you want and use the PostScript name of the font in your xcode project.
It should work even for different font variations of the same family.

Related

Debugging why specific font is not working in React Native

I am currently using many different fonts. All of them are working except for one particular.
I added it in the same way as I added others which are working:
Import the font into project
Modify info.plist
Find proper font family name (I did this by plugging NSLog inside RCTConvert)
Use the font in react-native through CSS with fontFamily
Unfortunately I cannot share the font publicly, so I have to ask how would one debug this issue?
One possible culprit is the font weight. I was trying to use a font with a weight of 325 at one point, but React Native seems to not allow the usage of a font unless the weight falls within their enum values (normal, bold, all hundreds within the range 100-900).
I used this app to modify the font weight of the file I was trying to use and set it to a standard 400: https://glyphsapp.com
In AppDelegate.m, under NSURL *jsCodeLocation, paste the following code. This will log out all available fonts, including the new font(s) that you have added:
for (NSString* family in [UIFont familyNames])
{
NSLog(#”%#”, family);
for (NSString* name in [UIFont fontNamesForFamilyName: family])
{
NSLog(#” %#”, name);
}
}
That way, you can get the exact font name to use in your app. The log output should look something like this:
I needed the same solution, using Swift. Here is the script to print out the Font Familes, and Faces, in Swift (works in appDelegate)
let fontFamilies = UIFont.familyNames()
for fontNames in fontFamilies{
print(fontNames)
let fontFace = UIFont.fontNamesForFamilyName(fontNames)
for aName in fontFace{
print(" \(aName)")
}
}[output of script][1]
link to part of log...http://www.zonesight.com/stackImages/font.png

How to use different fonts for different languages in an iOS application?

I am in a scenario where I want to use different fonts for the different languages in my iOS application.
At first, I thought of using localized versions of .ttf files. I tried adding the localized .ttf files in the localized project folders for different languages with the same filename and font-name installed in them. It didn't work.
I then looked into the InfoPlist.strings files for different languages. It appeared to me as the key value combination for the 'key' strings found in the main Info.plist. I found the font entry against the key 'UIAppFonts' which was an array. I am unable to figure out how to put the localized font file names in the InfoPlist.strings as an array.
As a last resort, I am thinking of adding localized font names in the Localizable.stings files to pick the font name according to the current locale and replace all the occurrences in my project wherever I have used fonts. (Obviously it is a lot cumbersome). Like:
UIFont *font = [UIFont fontWithName:NSLocalizedString(#"font-name", nil) size:16];
Please assist if anybody has done this before. It would be great if somehow one of the first two ideas can be implemented.
I actually have done this by adding different font files for different languages in the project and in the plist against UIAppFonts. Then I introduced:
"fontName" = "English Font";
"fontName" = "Russian Font";
in Localizable.strings for each supported language
I then accessed it using:
UIFont *font = [UIFont fontWithName:NSLocalizedString(#"fontName", nil) size:16];
As I mentioned in my question that the other two approaches seem to be more elegant. Any solution regarding those will be highly helpful.
To use specific UIFonts inside an app I created an extension of UIButton and UILabel. Because I had the same problem, choosing different UIFonts for different languages, I also inserted a check into my extension. What looked like:
#implementation MyButton{
NSString *_language;
}
- (void)awakeFromNib{
_language = [[NSLocale preferredLanguages] objectAtIndex:0];
[self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[self.titleLabel setFont:[self whichFontShouldBeUsed]];
}
- (UIFont *)whichFontShouldBeUsed{
UIFont *fontToUse = [UIFont fontWithName:#"Basic Font"
size:self.titleLabel.font.pointSize];
if( [_language isEqualToString:#"tr"] &&
[_language isEqualToString:#"pl"] ){
fontToUse = [UIFont fontWithName:#"Another Font"
size:self.titleLabel.font.pointSize];
} else if( [_language isEqualToString:#"ja"] &&
[_language isEqualToString:#"tr"] ){
fontToUse = [UIFont boldSystemFontOfSize:self.titleLabel.font.pointSize];
} else if( [_language isEqualToString:#"ru"] ){
fontToUse = [UIFont fontWithName:#"Another Font"
size:self.titleLabel.font.pointSize + 2.0f];
}
return fontToUse;
}
This way you can always switch UIFonts automatically. Next, you just have to add this class inside the Interface Builder. Select the UIButton you want and add your custom UIButton class:
For UILabel you would use setText instead of setTitleLabel" and setTextColorinstead ofsetTitleColor`.
For further information to preferredLanguages look at this website and of course don't forget to add your fonts to the projects Target and also to the plist.
You are on the right track with UIAppFonts. First, add the .ttf files to your project under the Resources folder. Then, you need to add a new line to the Info.plist (not InfoPlist.strings?). You do this by clicking on the Plus sign (+) at the far right of the last line in the plist, or I think You can Control-click any other property and select New. Select UIAppFonts from the drop-down in the first column, and that should put an arrow (>) to the left of it. Click on this arrow to expand the property and you should see item0, type in the name of your .ttf file there. Control-click to add more items as necessary.
This will add your custom fonts to the application. It is important to note that when you load them using fontWithName, the name you supply in #"font-name" may not (and usually IS NOT) the exact same name as the .ttf file. Rather, it is the whole name as it appears in the Font Book under Preview --> Show Font Info.
All this is fine, but it doesn't localize anything. You could use something like the line below to query the language code and then decide which font to load based on that:
NSString * language = [[NSLocale preferredLanguages] objectAtIndex:0];

Cant find custom font - iOS

i have added a custom font - one which i have downloaded from from the net. it is in TTF format and can be used on other programs on my mac. (Successfully added it to font book and used in fireworks).
I have added the key to the info .plist but the font doesn't seem to work.
When i NSLog the font it is null so i am assuming it isn't finding it.
The TTF is called LONDON__.TTF but has a name as London font.
What should i use as the font and add to the info.plist for this to work?
Thanks
Dan
Application fonts resource path = LONDON__.TTF
NSLog(#"%#",[UIFont fontWithName:#"London font" size:22]);
and
NSLog(#"%#",[UIFont fontWithName:#"LONDON__.TTF" size:22]);
Both of them return Null.
Although the file is named LONDON__.TTF the font appear as everyone in Font Book. is this the issue?
Look at all the available fonts
Objective-C:
for(NSString* family in [UIFont familyNames]) {
NSLog(#"%#", family);
for(NSString* name in [UIFont fontNamesForFamilyName: family]) {
NSLog(#" %#", name);
}
}
Swift:
for family: String in UIFont.familyNames() {
print("%#", family)
for name: String in UIFont.fontNamesForFamilyName(family) {
print(" %#", name)
}
}
..if it's not there, install again
Copy the .ttf file into your project (i.e. drag it to the resource folder in the Project navigator).
In your Info.plist add an entry with the key Fonts provided by application with an Array type. As Item 0, add a String value corresponding to the font file name (e.g. OpenSans-ExtraBoldItalic.ttf).
Make sure the font file is included in the copy bundle resources list under the project settings.
You need to make sure the font file is included in the copy bundle resources list under the project settings. My font wouldn't show up in [UIFont familyNames] till I added it here as it was not automatically included when added to the project.
Both of those names sound wrong. Assuming you've correctly added it to your plist, use something like
NSLog(#"Fonts: %#", [UIFont familyNames]);
to see what its internal name is.
BTW, be sure that the licensing of the font allows embedding. Many commercial fonts do not.

Custom Font in ios not working

I want to use HelveticaNeue-UltraLight in my ios application. I'm adding the font file as a resource to my project and adding the "Fonts provided by application" key in the plist file. The file name is HelveticaNeue.dfont and I've added it to the key array.
When I check for the available fonts I can see it now...
NSArray *fonts = [UIFont fontNamesForFamilyName:#"Helvetica Neue"];
for(NSString *string in fonts){
NSLog(#"%#", string);
}
1-07-08 17:32:57.866 myApp[5159:207] HelveticaNeue-Bold
2011-07-08 17:32:57.866 myApp[5159:207] HelveticaNeue-CondensedBlack
2011-07-08 17:32:57.867 myApp[5159:207] HelveticaNeue-Medium
2011-07-08 17:32:57.867 myApp[5159:207] HelveticaNeue
2011-07-08 17:32:57.868 myApp[5159:207] HelveticaNeue-Light
2011-07-08 17:32:57.868 myApp[5159:207] HelveticaNeue-CondensedBold
2011-07-08 17:32:57.868 myApp[5159:207] HelveticaNeue-LightItalic
2011-07-08 17:32:57.869 myApp[5159:207] HelveticaNeue-UltraLightItalic
2011-07-08 17:32:57.869 myApp[5159:207] HelveticaNeue-UltraLight // HERE IT IS!
2011-07-08 17:32:57.869 myApp[5159:207] HelveticaNeue-BoldItalic
2011-07-08 17:32:57.870 myApp[5159:207] HelveticaNeue-Italic
But when I try to get it with [UIFont fontWithName:#"HelveticaNeue-UltraLight" size:12] I just get HelveticaNeue-Light..
I'm getting no errors or warnings.
Help please!
Not only does the file needs to be added to the project, but it needs to be added to the target as well.
Sometimes (as in my case), when drag and dropping the ".ttf" file in Xcode, the "add to target" is not checked. This means the file is actually visible in your project, but it is not embedded in the app.
To make sure it is:
Click on the project's name (left pane)
Then on the target (middle pane)
Then "Build Phases" (third tab on the right pane)
Then "Copy Bundle Resources"
You should see the font file in that list.
I think you're having the same problem I had : there's a bug in iOS where it is not able to use more than 2 fonts from the same family.
See blog post here for details and solution : http://www.pixeldock.com/blog/uifont-problem-when-using-more-than-2-custom-fonts-of-the-same-font-family/
after adding Font file in Bundle
"Font Provided by Application" property click on drop down arrow
and enter your font name with extension
It is working with different variations of the same font(even in IOS 8). I'll post my mistake just in case someone has the same problem...
I was using font's filename instead of the font name.
A useful solution is print all the fonts available and look for the one I was using.
In Swift would be:
for fontFamilyNames in UIFont.familyNames {
for fontName in UIFont.fontNames(forFamilyName: fontFamilyNames) {
print("FONTNAME:\(fontName)")
}
}
I found this useful tutorial in: Code with Chris
Open Font Book application. If you installed the fonts yourself, go to user, look for the fonts you want and use the PostScript name of the font in your xcode project.
It should work even for different font variations of the same family.
Drag your font files (.ttf or .otf) into project's bundle.
Then select all those fonts > on your xcode's right panel make sure the Target membership is enabled.
Select project from the navigator panel > select Build phases > under Copy Bundle Resources verify all your fonts are listed. If not, add one by one using + icon.
Info.plist > select Fonts provided by application > add your fonts one by one (e.g., Helvetica-Bold.ttf).
While this probably won't help the OP, it might be useful to others.
With iOS 5, Helvetica Neue is automatically included; you don't have to add this custom font to the bundle. It's even possible to use that font family directly from Interface Builder, which is extremely handy.
Try this this will be also heleful for you.
[compete_Label setFont:[UIFont fontWithName:#"Helvetica-Bold" size:12]];
After spending hours, I came to know that the Name for the font we need to add is not the file name of the font but the actual Font name. I was trying to include font file bonveno.ttf. I have included the filename along with extension in info.plist and was able to see the font in the Copy Bundle Resources list. My code was like
self.label.font = [UIFont fontWithName:#"bonveno" size:30];
that was causing the problem. Then I double clicked the font file from Finder to see the preview of the font. That time I noticed the name of the font in the preview window as BonvenoCF. So I added that name in the code like
self.label.font = [UIFont fontWithName:#"BonvenoCF" size:30];
Worked like charm!! Can't live without this cute font in my apps.
Try with spaces:
[UIFont fontWithName:#"Helvetica Neue UltraLight" size:12];
See Certain fonts not showing up?
I ended up buying the font Helvetica Neue UltraLight from a third party, added it with no problems.
In order to use custom fonts in iOS, just add your fonts by drag & drop to your project. Mention the array of font names with extension in Info.plist with key "Fonts provided by application". Then print all font family names using below code :
for (NSString* family in [UIFont familyNames])
{
DebugLog(#"FONT FAMILY: %#", family);
for (NSString *name in [UIFont fontNamesForFamilyName: family])
{
DebugLog(#" %#", name);
}
}
Console print :
Arial Hebrew
ArialHebrew-Bold
ArialHebrew-Light
ArialHebrew
Calibri
Calibri-Bold
Calibri
Georgia
Georgia-BoldItalic
Georgia-Bold
Georgia-Italic
Georgia
Then from console, you will get the actual font-names (As above). Use below code to create font -
In core text :
CTFontRef fontRef = CTFontCreateWithName((CFStringRef)fontName, fontSize, NULL);
In UIKit :
UIFont *font = [UIFont fontWithName:fontName size:10];
Note : here fontName = #"Calibri-Bold" is without extension.
In addition to:
adding the font file names to the info.plist under "Fonts provided by
application"
adding the actual files to the project.
You also have to make sure that under Targets -> Build Phases -> Copy Bundle Resources has the actual filenames of the custom fonts.
To check if they have appeared, you can do something like:
UIFont.familyNames.forEach { (name) in
print(name)
}
Another thing to check is on a Mac: Open the app Font Book. Then go file -> file validation and open the font. If something is failing (even with a warning) in there iOS generally rejects loading the font in the app with no errors.
If this is the case then you can fix the errors by opening the font in a free app called "Typelight" And resaving the font "Save as".
In addition to the well explained #Ben answer, if you're still not getting your fonts, Just use or assign your font to any Label in one of your Storyboard, You will start getting it using this code
If you still unable to get font using [UIFont fontWithName:#"Font-Regular" size:11]; There must be problem in naming. Stop at any Breakpoint in debugger and Debug it using different names, and see which po prints object that is not nil
po [UIFont fontWithName:#"FontRegular" size:11];
or
po [UIFont fontWithName:#"Font Regular" size:11];
or
po [UIFont fontWithName:#"Font-Regular" size:11];
You will get <UICTFont: 0x7fe2044021d0> font-family: "Interstate-Regular"; font-weight: normal; font-style: normal; font-size: 11.00pt for actual font name otherwise you will get nil
note that add .ttf end of each Fonts provided by application name
It's an old question but I'd like to emphasize that we must write font file name WITH EXTENSION into info.plist.
It was particularly my mistake: I missed extensions. But the very interesting thing that iOS successfully loaded three fonts even when the extensions were missed.
Once I've added extensions all 12 fonts were loaded.
Good article:
https://codewithchris.com/common-mistakes-with-adding-custom-fonts-to-your-ios-app/

Can I embed a custom font in an iPhone application?

I would like to have an app include a custom font for rendering text, load it, and then use it with standard UIKit elements like UILabel. Is this possible?
iOS 3.2 and later support this. Straight from the What's New in iPhone OS 3.2 doc:
Custom Font Support
Applications that want to use custom fonts can now include those fonts in their application bundle and register those fonts with the system by including the UIAppFonts key in their Info.plist file. The value of this key is an array of strings identifying the font files in the application’s bundle. When the system sees the key, it loads the specified fonts and makes them available to the application.
Once the fonts have been set in the Info.plist, you can use your custom fonts as any other font in IB or programatically.
There is an ongoing thread on Apple Developer Forums:
https://devforums.apple.com/thread/37824 (login required)
And here's an excellent and simple 3 steps tutorial on how to achieve this (broken link removed)
Add your custom font files into your project using Xcode as a resource
Add a key to your Info.plist file called UIAppFonts.
Make this key an array
For each font you have, enter the full name of your font file (including the extension) as items to the UIAppFonts array
Save Info.plist
Now in your application you can simply call [UIFont fontWithName:#"CustomFontName" size:12] to get the custom font to use with your UILabels and UITextViews, etc…
Also: Make sure the fonts are in your Copy Bundle Resources.
Edit: As of iOS 3.2, this functionality is built in. If you need to support pre-3.2, you can still use this solution.
I created a simple module that extends UILabel and handles loading .ttf files. I released it opensource under the Apache license and put it on github Here.
The important files are FontLabel.h and FontLabel.m.
It uses some of the code from Genericrich's answer.
Browse the source Here.
OR
Copy your font file into resources
Add a key to your Info.plist file called UIAppFonts. ("Fonts provided by application)
Make this key an array
For each font you have, enter the full name of your font file (including the extension) as items to the UIAppFonts array
Save Info.plist
Now in your application you can simply call [UIFont fontWithName:#"CustomFontName" size:15] to get the custom font to use with your UILabels and UITextViews, etc…
For More Information
There is a simple way to use custom fonts in iOS 4.
Add your font file (for example, Chalkduster.ttf) to Resources folder of the project in XCode.
Open info.plist and add a new key called UIAppFonts. The type of this key should be array.
Add your custom font name to this array including extension (Chalkduster.ttf).
Now you can use [UIFont fontWithName:#"Chalkduster" size:16] in your application.
Unfortunately, IB doesn't allow to initialize labels with custom fonts. See this question to solve this problem. My favorite solution is to use custom UILabel subclass:
#implementation CustomFontLabel
- (id)initWithCoder:(NSCoder *)decoder
{
if (self = [super initWithCoder: decoder])
{
[self setFont: [UIFont fontWithName: #"Chalkduster" size: self.font.pointSize]];
}
return self;
}
#end
In Info.plist add the entry "Fonts provided by application" and include the font names as strings:
Fonts provided by application
Item 0 myfontname.ttf
Item 1 myfontname-bold.ttf
...
Then check to make sure your font is included by running :
for (NSString *familyName in [UIFont familyNames]) {
for (NSString *fontName in [UIFont fontNamesForFamilyName:familyName]) {
NSLog(#"%#", fontName);
}
}
Note that your ttf file name might not be the same name that you use when you set the font for your label (you can use the code above to get the "fontWithName" parameter):
[label setFont:[UIFont fontWithName:#"MyFontName-Regular" size:18]];
edit: This answer is defunct as of iOS3.2; use UIAppFonts
The only way I've been able to successfully load custom UIFonts is via the private GraphicsServices framework.
The following will load all the .ttf fonts in the application's main bundle:
BOOL GSFontAddFromFile(const char * path);
NSUInteger loadFonts()
{
NSUInteger newFontCount = 0;
for (NSString *fontFile in [[NSBundle mainBundle] pathsForResourcesOfType:#"ttf" inDirectory:nil])
newFontCount += GSFontAddFromFile([fontFile UTF8String]);
return newFontCount;
}
Once fonts are loaded, they can be used just like the Apple-provided fonts:
NSLog(#"Available Font Families: %#", [UIFont familyNames]);
[label setFont:[UIFont fontWithName:#"Consolas" size:20.0f]];
GraphicsServices can even be loaded at runtime in case the API disappears in the future:
#import <dlfcn.h>
NSUInteger loadFonts()
{
NSUInteger newFontCount = 0;
NSBundle *frameworkBundle = [NSBundle bundleWithIdentifier:#"com.apple.GraphicsServices"];
const char *frameworkPath = [[frameworkBundle executablePath] UTF8String];
if (frameworkPath) {
void *graphicsServices = dlopen(frameworkPath, RTLD_NOLOAD | RTLD_LAZY);
if (graphicsServices) {
BOOL (*GSFontAddFromFile)(const char *) = dlsym(graphicsServices, "GSFontAddFromFile");
if (GSFontAddFromFile)
for (NSString *fontFile in [[NSBundle mainBundle] pathsForResourcesOfType:#"ttf" inDirectory:nil])
newFontCount += GSFontAddFromFile([fontFile UTF8String]);
}
}
return newFontCount;
}
With iOS 8+ and Xcode 6+ you can make this easily. Here are the steps:
1) Drag and drop your font to Xcode Supporting Files folder. Don't forget to mark your app at Add to targets section. From this moment you can use this font in IB and choose it from font pallet.
2) To make this font available to in your device, open your info.plist and add Fonts provided by application key. It will contain Item 0 key, you must add your font name as the value. Font name can vary from your font file name. But first, try to add your filename in most cases this work.
If not, this article always helped me.
Here is swift snippet of the code from this article to help you find your font name.
func allFonts(){
for family in UIFont.familyNames(){
println(family)
for name in UIFont.fontNamesForFamilyName(family.description)
{
println(" \(name)")
}
}
}
EDIT
I want to mention, that you need to add font files to your Target's Build Phases, Copy Bundle Resources. Without it, you won't see your font on the device. And it could lead to unexpected behaviour.
For example, I encounter a bug, when UITextField have custom font, but this font wasn't in the Copy Bundle Resources. And when I segue to the viewcontroller with this textfield, there is a delay about 4 seconds before viewDidLoad function was called. Resolving font troubles removed this delay. So, recommend to check it twice. (rdar://20028250) Btw, I wasn't able to reproduce the bug, but I'm sure that problem was with the font.
I have done this like this:
Load the font:
- (void)loadFont{
// Get the path to our custom font and create a data provider.
NSString *fontPath = [[NSBundle mainBundle] pathForResource:#"mycustomfont" ofType:#"ttf"];
CGDataProviderRef fontDataProvider = CGDataProviderCreateWithFilename([fontPath UTF8String]);
// Create the font with the data provider, then release the data provider.
customFont = CGFontCreateWithDataProvider(fontDataProvider);
CGDataProviderRelease(fontDataProvider);
}
Now, in your drawRect:, do something like this:
-(void)drawRect:(CGRect)rect{
[super drawRect:rect];
// Get the context.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, rect);
// Set the customFont to be the font used to draw.
CGContextSetFont(context, customFont);
// Set how the context draws the font, what color, how big.
CGContextSetTextDrawingMode(context, kCGTextFillStroke);
CGContextSetFillColorWithColor(context, self.fontColor.CGColor);
UIColor * strokeColor = [UIColor blackColor];
CGContextSetStrokeColorWithColor(context, strokeColor.CGColor);
CGContextSetFontSize(context, 48.0f);
// Create an array of Glyph's the size of text that will be drawn.
CGGlyph textToPrint[[self.theText length]];
// Loop through the entire length of the text.
for (int i = 0; i < [self.theText length]; ++i) {
// Store each letter in a Glyph and subtract the MagicNumber to get appropriate value.
textToPrint[i] = [[self.theText uppercaseString] characterAtIndex:i] + 3 - 32;
}
CGAffineTransform textTransform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
CGContextSetTextMatrix(context, textTransform);
CGContextShowGlyphsAtPoint(context, 20, 50, textToPrint, [self.theText length]);
}
Basically you have to do some brute force looping through the text and futzing about with the magic number to find your offset (here, see me using 29) in the font, but it works.
Also, you have to make sure the font is legally embeddable. Most aren't and there are lawyers who specialize in this sort of thing, so be warned.
Yes, you can include custom fonts. Refer to the documentation on UIFont, specifically, the fontWithName:size: method.
1) Make sure you include the font in your resources folder.
2) The "name" of the font is not necessarily the filename.
3) Make sure you have the legal right to use that font. By including it in your app, you're also distributing it, and you need to have the right to do that.
If you are using xcode 4.3, you have to add the font to the Build Phase under Copy Bundle Resources, according to https://stackoverflow.com/users/1292829/arne in the thread, Custom Fonts Xcode 4.3. This worked for me, here are the steps I took for custom fonts to work in my app:
Add the font to your project. I dragged and dropped the OTF (or TTF) files to a new group I created and accepted xcode's choice of copying the files over to the project folder.
Create the UIAppFonts array with your fonts listed as items within the array. Just the names, not the extension (e.g. "GothamBold", "GothamBold-Italic").
Click on the project name way at the top of the Project Navigator on the left side of the screen.
Click on the Build Phases tab that appears in the main area of xcode.
Expand the "Copy Bundle Resources" section and click on "+" to add the font.
Select the font file from the file navigator that pops open when you click on the "+".
Do this for every font you have to add to the project.
I would recommend following one of my favorite short tutorials here: http://codewithchris.com/common-mistakes-with-adding-custom-fonts-to-your-ios-app/ from which this information comes.
Step 1 - Drag your .ttf or .otf from Finder into your Project
NOTE - Make sure to click the box to 'Add to targets' on your main application target
If you forgot to click to add it to your target then click on the font file in your project hierarchy and on the right side panel click the main app target in the Target Membership section
To make sure your fonts are part of your app target make sure they show up in your Copy Bundle Resources in Build Phases
Step 2 - Add the font file names to your Plist
Go to the Custom iOS Target Properties in your Info Section and add a key to the items in that section called Fonts provided by application (you should see it come up as an option as you type it and it will set itself up as an array. Click the little arrow to open up the array items and type in the names of the .ttf or .otf files that you added to let your app know that these are the font files you want available
NOTE - If your app crashes right after this step then check your spelling on the items you add here
Step 3 - Find out the names of your fonts so you can call them
Quite often the font name seen by your application is different from what you think it is based on the filename for that font, put this in your code and look over the log your application makes to see what font name to call in your code
Swift
for family: String in UIFont.familyNames(){
print("\(family)")
for names: String in UIFont.fontNamesForFamilyName(family){
print("== \(names)")
}
}
Objective C
for (NSString* family in [UIFont familyNames]){
NSLog(#"%#", family);
for (NSString* name in [UIFont fontNamesForFamilyName: family]){
NSLog(#" %#", name);
}
}
Your log should look something like this:
Step 4 - Use your new custom font using the name from Step 3
Swift
label.font = UIFont(name: "SourceSansPro-Regular", size: 18)
Objective C
label.font = [UIFont fontWithName:#"SourceSansPro-Regular" size:18];
Here's the step by step instructions how to do it. No need extra library or any special coding.
http://shang-liang.com/blog/custom-fonts-in-ios4/
Most of the time the issue is with the font not the method. The best way to do it is to use a font that for sure will work, like verdana or geogia. Then change to the intended font. If it does not work, maybe the font name is not right, or the font is not a well formated font.
It is very easy to add a new font on your existing iOS App.
You just need to add the font e.g. font.ttf into your Resource Folder.
Open your application info.plist. Add a new row as "Fonts provided by application" and type the font name as font.ttf.
And when setting the font do as setFont:"corresponding Font Name"
You can check whether your font is added or not by NSArray *check = [UIFont familyNames];.
It returns all the font your application support.
Find the TTF in finder and "Get Info". Under the heading "Full name:" it gave me a name which I then used with fontWithName (I just copied and pasted the exact name, in this case no '.ttf' extension was necessary).
It's not out yet, but the next version of cocos2d (2d game framework) will support variable length bitmap fonts as character maps.
http://code.google.com/p/cocos2d-iphone/issues/detail?id=317
The author doesn't have a nailed down release date for this version, but I did see a posting that indicated it would be in the next month or two.
One important notice: You should use the "PostScript name" associated with the font, not its Full name or Family name. This name can often be different from the normal name of the font.
follow this step
1)Copy your font in your project
2)open your .plist file in source code mode...(Note- Dont open info.plist)
3)Before that - Right click on your font and open it in fontforge or similar editor and install it in your system ,It should be install
4)Type this
<key>UIAppFonts</key>
<array>
<string>MyriadPro.otf</string>
</array>
5)Type this code in your class .m
[lblPoints setFont:[UIFont fontWithName:#"Myriad Pro" size:15.0]];
Here lblPoints will be change as of your UILabel
Done!!
If still your font not work,check your fonts compatibility first
Maybe the author forgot to give the font a Mac FOND name?
Open the font in FontForge then go to Element>Font Info
There is a "Mac" Option where you can set the FOND name.
Under File>Export Font you can create a new ttf
You could also give the "Apple" option in the export dialog a try.
DISCLAIMER: I'm not a IPhone developer!
I have been trying out the various suggestions on this page on iOS 3.1.2 and these are my conclusions:
Simply using [UIFont fontWithName:size:] with the fonts in the Resources directory will not work, even if the FOND name is set using FontForge.
[UIFont fontWithName:size:] will work if the fonts are loaded first using GSFontAddFromFile. But GSFontAddFromFile is not part of iOS 3.1.2 so it has to be dynamically loaded as described by #rpetrich.
Look up ATSApplicationFontsPath
A simple plist entry that allows you to include the font file(s) in your app resources folder and they "just work" in your app.
I've combined some of the advice on this page into something that works for me on iOS 5.
First, you have to add the custom font to your project. Then, you need to follow the advice of #iPhoneDev and add the font to your info.plist file.
After you do that, this works:
UIFont *yourCustomFont = [UIFont fontWithName:#"YOUR-CUSTOM-FONT-POSTSCRIPT-NAME" size:14.0];
[yourUILabel setFont:yourCustomFont];
However, you need to know the Postscript name of your font. Just follow #Daniel Wood's advice and press command-i while you're in FontBook.
Then, enjoy your custom font.
First add the font in .odt format to your resources, in this case we will use DINEngschriftStd.otf, then use this code to assign the font to the label
[theUILabel setFont:[UIFont fontWithName:#"DINEngschriftStd" size:21]];
To make sure your font is loaded on the project just call
NSLog(#"Available Font Families: %#", [UIFont familyNames]);
On the .plist you must declare the font. Just add a 'Fonts provided by application' record and add a item 0 string with the name of the font (DINEngschriftStd.otf)
For iOS 3.2 and above:
Use the methods provided by several above, which are:
Add your font file (for example, Chalkduster.ttf) to Resources folder of the project in XCode.
Open info.plist and add a new key called UIAppFonts. The type of this key should be array.
Add your custom font name to this array including extension ("Chalkduster.ttf").
Use [UIFont fontWithName:#"Real Font Name" size:16] in your application.
BUT
The "Real Font Name" is not always the one you see in Fontbook. The best way is to ask your device which fonts it sees and what the exact names are.
I use the uifont-name-grabber posted at:
uifont-name-grabber
Just drop the fonts you want into the xcode project, add the file name to its plist, and run it on the device you are building for, it will email you a complete font list using the names that UIFont fontWithName: expects.
Better solution is to add a new property "Fonts provided by application" to your info.plist file.
Then, you can use your custom font like normal UIFont.
There is a new way to use custom fonts, starting with iOS 4.1. It allows you to load fonts dynamically, be they from files included with the app, downloaded data, or what have you. It also lets you load fonts as you need them, whereas the old method loads them all at app startup time, which can take too long if you have many fonts.
The new method is described at ios-dynamic-font-loading
You use the CTFontManagerRegisterGraphicsFont function, giving it a buffer with your font data. It's then available to UIFont and web views, just as with the old method. Here's the sample code from that link:
NSData *inData = /* your font-file data */;
CFErrorRef error;
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)inData);
CGFontRef font = CGFontCreateWithDataProvider(provider);
if (! CTFontManagerRegisterGraphicsFont(font, &error)) {
CFStringRef errorDescription = CFErrorCopyDescription(error)
NSLog(#"Failed to load font: %#", errorDescription);
CFRelease(errorDescription);
}
CFRelease(font);
CFRelease(provider);
Swift, code way: (works also with swift 2.0)
Add the required fonts to your project (just like adding images, just drag to Xcode), make sure that they are targeted to your project
add this method and load custom fonts (recommended in appDelegate didFinishLaunchingWithOptions)
func loadFont(filePath: String) {
let fontData = NSData(contentsOfFile: filePath)!
let dataProvider = CGDataProviderCreateWithCFData(fontData)
let cgFont = CGFontCreateWithDataProvider(dataProvider)!
var error: Unmanaged<CFError>?
if !CTFontManagerRegisterGraphicsFont(cgFont, &error) {
let errorDescription: CFStringRef = CFErrorCopyDescription(error!.takeUnretainedValue())
print("Unable to load font: %#", errorDescription, terminator: "")
}
}
Use example:
if let fontPath = NSBundle.mainBundle().pathForResource("My-Font", ofType: "ttf"){
loadFont(fontPath)
}
Use the font:
UIFont(name: "My-Font", size: 16.5)
You can add the required "FONT" files within the resources folder. Then go to the Project Info.plist file and use the KEY "Fonts provided by the application" and value as "FONT NAME".
Then you can call the method [UIFont fontwithName:#"FONT NAME" size:12];
I made everything possible but the new fonts dont appear so I found the solution:
When you drag the fot files(otf or ttf) DONT forget to check the checkbox under "Add to targets".
After doing that your font will appear and everything will work fine.
Although some of the answers above are correct, I have written a detailed visual tutorial for people still having problems with fonts.
The solutions above which tell you to add the font to the plist and use
[self.labelOutlet setFont:[UIFont fontWithName:#"Sathu" size:10]];
are the correct ones. Please do now use any other hackish way. If you are still facing problems with finding font names and adding them, here is the tutorial -
Using custom fonts in ios application
yes you can use custom font in your application
step by step following there:
Add your custom font files into your project in supporting files
Add a key to your Info.plist file called UIAppFonts.
Make this key an array
For each font you have, enter the full name of your font file (including the extension) as items to the UIAppFonts array
Save Info.plist Now in your application you can simply call [UIFont fontWithName:#"your Custom font Name" size:20] to get the custom font to use with your UILabels
after applying this if your not getting correct font then you double click on the custom font , and see carefully top side font name is comming and copy this font , paste, here [UIFont fontWithName:#" here past your Custom font Name" size:20]
i hope you will get correct answer
yes you can use custom font in your application
step by step following there:
Add your custom font files into your project in supporting files
Add a key to your Info.plist file called UIAppFonts.
Make this key an array
For each font you have, enter the full name of your font file (including the extension) as items to the UIAppFonts array
Save Info.plist
Now in your application you can simply call [UIFont fontWithName:#"your Custom font Name" size:20] to get the custom font to use with your UILabels
after applying this if your not getting correct font
then you double click on the custom font , and see carefully top side font name is comming
and copy this font , paste, here [UIFont fontWithName:#" here past your Custom font Name" size:20]
i hope you will get correct answer

Resources