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


当前回答

编辑:从iOS 3.2开始,这个功能是内置的。如果您需要支持3.2版本,您仍然可以使用这个解决方案。

我创建了一个扩展UILabel并处理加载.ttf文件的简单模块。我在Apache许可下发布了它,并把它放在github这里。

重要的文件是FontLabel.h和FontLabel.m。

它使用了Genericrich回答中的一些代码。

在这里浏览源代码。

OR

复制您的字体文件到资源 为你的信息添加一个键。名为UIAppFonts的plist文件。("应用程序提供的字体) 将该键设置为数组 对于你拥有的每种字体,输入字体文件的全名(包括扩展名)作为UIAppFonts数组的项 保存Info.plist 现在在你的应用程序中,你可以简单地调用[UIFont fontWithName:@"CustomFontName" size:15]来获得自定义字体来使用你的UILabels和UITextViews等…

更多信息

其他回答

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

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

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

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

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

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

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 5上使用的东西。

首先,您必须将自定义字体添加到项目中。然后,您需要按照@iPhoneDev的建议,将字体添加到您的信息中。plist文件。

在你这样做之后,这是有效的:

UIFont *yourCustomFont = [UIFont fontWithName:@"YOUR-CUSTOM-FONT-POSTSCRIPT-NAME" size:14.0];
[yourUILabel setFont:yourCustomFont];

但是,您需要知道字体的Postscript名称。只要遵循@Daniel Wood的建议,在FontBook中按command-i即可。

然后,享受您的自定义字体。

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