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


当前回答

如果你使用的是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.

其他回答

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

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

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

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

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

是的,您可以包括自定义字体。参考UIFont的文档,特别是fontWithName:size:方法。

1)确保在你的资源文件夹中包含了该字体。

2)字体的“名称”不一定是文件名。

3)确保你有使用这种字体的合法权利。通过把它包含在你的应用中,你也在传播它,你需要有这样做的权利。

Swift,代码方式:(也适用于Swift 2.0)

添加所需的字体到你的项目(就像添加图像,只需拖动到Xcode),确保他们是针对你的项目 添加这个方法并加载自定义字体(推荐在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: "")
    }

}

使用的例子:

if let fontPath = NSBundle.mainBundle().pathForResource("My-Font", ofType: "ttf"){
      loadFont(fontPath)
}

使用字体:

UIFont(name: "My-Font", size: 16.5)

正如之前所有的答案所表明的,这是非常有可能的,而且在更新的iOS版本中非常容易。

我知道这不是一个技术上的答案,但因为很多人都做错了(这实际上违反了许可,如果你被起诉,可能会花费你很多钱),让我在这里强调一个警告:在iOS(或任何其他类型)应用程序中嵌入自定义字体基本上是重新分配字体。大多数商业字体的许可都禁止再分发,所以请确保您按照许可行事。

我在iOS 3.1.2上尝试了这个页面上的各种建议,以下是我的结论:

简单地使用[UIFont fontWithName:size:]与资源目录中的字体将不起作用,即使使用FontForge设置了FOND名称。

[UIFont fontWithName:size:]将工作,如果字体首先使用GSFontAddFromFile加载。但是GSFontAddFromFile不是iOS 3.1.2的一部分,所以它必须像@rpetrich所描述的那样动态加载。