UIFont fontWithName返回nil

Roe*_*dam 9 objective-c uifont

此代码以字体形式返回Me nil.

我将open sans ttf文件添加到项目文件夹中.

我错过了什么?

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;
    }
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

deh*_*len 12

首先是你的.plist文件中注册的.ttf 文件?第二个是你的字体添加到" 复制捆绑资源 "?(在Target-> Build阶段下)

接下来尝试使用此代码列出所有可用字体及其名称.这样,您可以确保为字体使用正确的标识符.

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

编辑

由于这个答案有点旧,我用Swift 3.0的相应答案更新了它:

_ = UIFont.familyNames.map {
    let fontNames = UIFont.fontNames(forFamilyName: $0)
    print("Font Family: \($0), Font Names: \(fontNames)\n")
}
Run Code Online (Sandbox Code Playgroud)