Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIFont fontWithName return nil

This code return Me nil in font.

I add the open sans ttf file to project folder.

What am I missing?

UIFont *font = [UIFont fontWithName:@"OpenSans-Bold" size:fontSize];
    if (font)
    {
        [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:font size:fontSize] range:NSMakeRange(location, length)];
        label.attributedText = str;
    }

enter image description here

like image 216
Roei Nadam Avatar asked Apr 20 '15 07:04

Roei Nadam


1 Answers

First of all are your .ttf files registered in your .plist file ? Second are your fonts added to "Copy Bundle Resources" ? (Under Target->Build Phases)

Next try this code to list all usable fonts and their names. This way you can make sure you use the right identifier for your font.

for (NSString* fontFamily in [UIFont familyNames]) {
    NSArray *fontNames = [UIFont fontNamesForFamilyName:fontFamily];
    NSLog (@"%@: %@", fontFamily, fontNames);
}

Edit

Since this answer is a bit old I updated it with the corresponding answer for Swift 3.0:

_ = UIFont.familyNames.map {
    let fontNames = UIFont.fontNames(forFamilyName: $0)
    print("Font Family: \($0), Font Names: \(fontNames)\n")
}
like image 109
dehlen Avatar answered Nov 15 '22 23:11

dehlen