简体   繁体   中英

Set bold font to NSString iOS

I have imported 2 font files to my resources group in my project, and also added them to my plist file:

pt-sans.narrow-bold.ttf and PT_Sans-Narrow-Web-Bold.ttf

I want to set bold font to attributed string, but it can't find my fonts, i am getting this error:

(UIFont*) nil

This is how i am setting the font:

UIFont *font_bold=[UIFont fontWithName:@"PT Sans Narrow Bold" size:14.0f];

It needs to be font from this family. Any idea, what am i doing wrong?

You can check the font's are accessible by adding this to your didFinishLaunchingWithOptions

    NSArray *fontFamilies = [UIFont familyNames];

for (int i = 0; i < [fontFamilies count]; i++)
{
    NSString *fontFamily = [fontFamilies objectAtIndex:i];
    NSArray *fontNames = [UIFont fontNamesForFamilyName:[fontFamilies objectAtIndex:i]];
    NSLog (@"%@: %@", fontFamily, fontNames);
}

and as @mikle94 said, caps is probably your issue.

In cases where we want to use fonts in our app, which don't already exist, we should pay attention to the several things, in order not to do the same mistake i did, and after that wonder "what is wrong, my code is perfectly written".

  1. Copy the font in .otf or .ttf to your project.

  2. Add it to the .plist file. Add 'Fonts provided by application' key in your plist file and in Item 0 copy the font name, which you already imported to your project.

  3. Check in your Target -> Build Phases -> Copy Bundle Resources. If you don't see your font in there, add it.

  4. Very Important - List the available fonts to check the correct names which you can use in your app:

     NSArray *fontFamilies = [UIFont familyNames]; for (int i = 0; i < [fontFamilies count]; i++) { NSString *fontFamily = [fontFamilies objectAtIndex:i]; NSArray *fontNames = [UIFont fontNamesForFamilyName:[fontFamilies objectAtIndex:i]]; NSLog (@"%@: %@", fontFamily, fontNames); } 

Find the font you need and set it this way:

UIFont *customFont = [UIFont fontWithName:@"PTSans-NarrowBold" size:20];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM