我想有一个应用程序包括一个自定义字体渲染文本,加载它,然后使用它与标准UIKit元素如UILabel。这可能吗?


当前回答

一个重要的注意事项:您应该使用与字体相关的“PostScript名称”,而不是其全名或家族名称。此名称通常与字体的正常名称不同。

其他回答

更好的解决方案是在你的信息中添加一个新的属性“应用程序提供的字体”。plist文件。

然后,你可以使用你的自定义字体像正常的UIFont。

我建议大家参考我最喜欢的一个简短教程:http://codewithchris.com/common-mistakes-with-adding-custom-fonts-to-your-ios-app/,上面的信息都来自这个网站。

第1步-将.ttf或.otf从Finder拖到项目中

注意-请确保在主应用程序目标上单击“添加到目标”框

如果你忘记单击将其添加到目标,然后单击项目层次结构中的字体文件,在右侧面板中单击目标会员部分中的主应用程序目标

要确保字体是应用目标的一部分,请确保它们出现在构建阶段的Copy Bundle Resources中

步骤2 -添加字体文件名到你的Plist

去自定义iOS目标属性在你的信息部分,并添加一个关键字,在该部分的项目,称为字体提供的应用程序(你应该看到它作为一个选项,当你输入它,它将自己设置为一个数组。点击小箭头打开数组项,输入你添加的.ttf或.otf文件的名称,让你的应用程序知道这些是你想要可用的字体文件

注意-如果你的应用程序在这一步之后崩溃,那么检查你在这里添加的项目的拼写

步骤3 -找出字体的名称,这样你就可以调用它们

通常情况下,应用程序看到的字体名称与基于该字体的文件名所认为的不同,将其放入代码中,并查看应用程序所做的日志,以查看在代码中调用的字体名称

斯威夫特

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);
    }
}

你的日志应该是这样的:

步骤4 -使用步骤3中的名称使用新的自定义字体

斯威夫特

 label.font = UIFont(name: "SourceSansPro-Regular", size: 18)

Objective - C

 label.font = [UIFont fontWithName:@"SourceSansPro-Regular" size:18];

虽然上面的一些答案是正确的,但我已经为那些仍然对字体有问题的人写了一个详细的可视化教程。

上面的解决方案告诉你将字体添加到plist并使用

[self.labelOutlet setFont:[UIFont fontWithName:@"Sathu" size:10]];

都是正确的。现在请使用任何其他的黑客方式。如果您仍然面临查找字体名称和添加它们的问题,这里是教程-

在ios应用程序中使用自定义字体

在信息。plist添加“Fonts provided by application”条目,并以字符串的形式包含字体名称:

Fonts provided by application
           Item 0        myfontname.ttf
           Item 1        myfontname-bold.ttf
           ...

然后运行以下命令,确保包含了你的字体:

for (NSString *familyName in [UIFont familyNames]) {
    for (NSString *fontName in [UIFont fontNamesForFamilyName:familyName]) {
         NSLog(@"%@", fontName);
    }
}

请注意,您的ttf文件名可能与您设置标签字体时使用的名称不同(您可以使用上面的代码来获得"fontWithName"参数):

[label setFont:[UIFont fontWithName:@"MyFontName-Regular" size:18]];

如果你使用的是xcode 4.3,你必须将字体添加到拷贝Bundle资源下的构建阶段,根据线程https://stackoverflow.com/users/1292829/arne,自定义字体xcode 4.3。这对我来说很有效,下面是我在应用程序中使用自定义字体的步骤:

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.