我可以在 iPhone 应用程序中嵌入自定义字体吗?

发布于 2024-07-09 12:13:29 字数 101 浏览 7 评论 0原文

我希望有一个应用程序包含用于渲染文本的自定义字体,加载它,然后将其与标准 UIKit 元素(如 UILabel)一起使用。 这可能吗?

I would like to have an app include a custom font for rendering text, load it, and then use it with standard UIKit elements like UILabel. Is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

何以畏孤独 2024-07-16 12:13:29

iOS 3.2 及更高版本支持此功能。 直接来自 iPhone OS 3.2 的新增功能 文档:

自定义字体支持
想要使用自定义字体的应用程序现在可以将这些字体包含在其应用程序包中,并通过在其 Info.plist 文件中包含 UIAppFonts 键来向系统注册这些字体。 该键的值是一个字符串数组,用于标识应用程序包中的字体文件。 当系统看到该密钥时,它会加载指定的字体并使它们可供应用程序使用。

Info.plist 中设置字体后,您可以像 IB 中的任何其他字体一样使用自定义字体或以编程方式使用。

Apple 开发者论坛上有一个正在进行的主题:
https://devforums.apple.com/thread/37824(需要登录)

这是一个很棒的以及关于如何实现此目的的简单 3 步教程(已删除损坏的链接)

  1. 使用 Xcode 作为资源将自定义字体文件添加到项目
  2. 中将密钥添加到名为 UIAppFonts< 的 Info.plist 文件中/代码>。
  3. 将此键设置为数组
  4. 对于您拥有的每种字体,输入字体文件的完整名称(包括扩展名)作为 UIAppFonts 数组中的项目
  5. Save Info.plist
  6. Now in在您的应用程序中,您只需调用[UIFont fontWithName:@"CustomFontName" size:12]即可获取与您的UILabelsUITextViews 等...

另外:确保字体位于您的复制捆绑资源中。

iOS 3.2 and later support this. Straight from the What's New in iPhone OS 3.2 doc:

Custom Font Support
Applications that want to use custom fonts can now include those fonts in their application bundle and register those fonts with the system by including the UIAppFonts key in their Info.plist file. The value of this key is an array of strings identifying the font files in the application’s bundle. When the system sees the key, it loads the specified fonts and makes them available to the application.

Once the fonts have been set in the Info.plist, you can use your custom fonts as any other font in IB or programatically.

There is an ongoing thread on Apple Developer Forums:
https://devforums.apple.com/thread/37824 (login required)

And here's an excellent and simple 3 steps tutorial on how to achieve this (broken link removed)

  1. Add your custom font files into your project using Xcode as a resource
  2. Add a key to your Info.plist file called UIAppFonts.
  3. Make this key an array
  4. For each font you have, enter the full name of your font file (including the extension) as items to the UIAppFonts array
  5. Save Info.plist
  6. Now in your application you can simply call [UIFont fontWithName:@"CustomFontName" size:12] to get the custom font to use with your UILabels and UITextViews, etc…

Also: Make sure the fonts are in your Copy Bundle Resources.

人海汹涌 2024-07-16 12:13:29

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

我创建了一个扩展 UILabel 并处理加载 .ttf 文件。 并将其放在 github 这里。

我在 Apache 许可证下开源发布了它, 文件是 FontLabel.hFontLabel.m

它使用 Genericrich 的一些代码回答

浏览源此处。

  • 将字体文件复制到资源中

  • 向您的 Info.plist 文件添加一个名为 UIAppFonts 的密钥。 (“应用程序提供的字体)

  • 数组

  • 对于您拥有的每种字体,输入字体文件的全名(包括扩展名)作为 UIAppFonts 数组的项目

  • Save Info.plist

  • 现在,在您的应用程序中,您可以简单地调用 [UIFont fontWithName:@"CustomFontName" size:15] 获取与您的 UILabelsUITextViews 等一起使用的自定义字体...< /p>

了解更多信息

Edit: As of iOS 3.2, this functionality is built in. If you need to support pre-3.2, you can still use this solution.

I created a simple module that extends UILabel and handles loading .ttf files. I released it opensource under the Apache license and put it on github Here.

The important files are FontLabel.h and FontLabel.m.

It uses some of the code from Genericrich's answer.

Browse the source Here.

OR

  • Copy your font file into resources

  • Add a key to your Info.plist file called UIAppFonts. ("Fonts provided by application)

  • Make this key an array

  • For each font you have, enter the full name of your font file (including the extension) as items to the UIAppFonts array

  • Save Info.plist

  • Now in your application you can simply call [UIFont fontWithName:@"CustomFontName" size:15] to get the custom font to use with your UILabels and UITextViews, etc…

For More Information

甜妞爱困 2024-07-16 12:13:29

iOS 4 中有一种使用自定义字体的简单方法。

  1. 将字体文件(例如 Chalkduster.ttf)添加到 XCode 中项目的 Resources 文件夹中。
  2. 打开 info.plist 并添加一个名为 UIAppFonts 的新键。 该键的类型应该是数组。
  3. 将您的自定义字体名称添加到此数组,包括扩展名 (Chalkduster.ttf)。
  4. 现在您可以在应用程序中使用[UIFont fontWithName:@"Chalkduster" size:16]

不幸的是,IB 不允许使用自定义字体初始化标签。 请参阅此问题来解决此问题。 我最喜欢的解决方案是使用自定义 UILabel 子类:

@implementation CustomFontLabel

- (id)initWithCoder:(NSCoder *)decoder
{
    if (self = [super initWithCoder: decoder])
    {
        [self setFont: [UIFont fontWithName: @"Chalkduster" size: self.font.pointSize]];
    }
    return self;
}

@end

There is a simple way to use custom fonts in iOS 4.

  1. Add your font file (for example, Chalkduster.ttf) to Resources folder of the project in XCode.
  2. Open info.plist and add a new key called UIAppFonts. The type of this key should be array.
  3. Add your custom font name to this array including extension (Chalkduster.ttf).
  4. Now you can use [UIFont fontWithName:@"Chalkduster" size:16] in your application.

Unfortunately, IB doesn't allow to initialize labels with custom fonts. See this question to solve this problem. My favorite solution is to use custom UILabel subclass:

@implementation CustomFontLabel

- (id)initWithCoder:(NSCoder *)decoder
{
    if (self = [super initWithCoder: decoder])
    {
        [self setFont: [UIFont fontWithName: @"Chalkduster" size: self.font.pointSize]];
    }
    return self;
}

@end
你如我软肋 2024-07-16 12:13:29

在 Info.plist 中添加条目“应用程序提供的字体”并将字体名称包含为字符串:

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]];

In Info.plist add the entry "Fonts provided by application" and include the font names as strings:

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

Then check to make sure your font is included by running :

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

Note that your ttf file name might not be the same name that you use when you set the font for your label (you can use the code above to get the "fontWithName" parameter):

[label setFont:[UIFont fontWithName:@"MyFontName-Regular" size:18]];
可可 2024-07-16 12:13:29

编辑:此答案从 iOS3.2 起已失效; 使用 UIAppFonts

我能够成功加载自定义 UIFont 的唯一方法是通过私有 GraphicsServices 框架。

以下将加载应用程序主包中的所有 .ttf 字体:

BOOL GSFontAddFromFile(const char * path);
NSUInteger loadFonts()
{
    NSUInteger newFontCount = 0;
    for (NSString *fontFile in [[NSBundle mainBundle] pathsForResourcesOfType:@"ttf" inDirectory:nil])
        newFontCount += GSFontAddFromFile([fontFile UTF8String]);
    return newFontCount;
}

加载字体后,可以像 Apple 提供的字体一样使用它们:

NSLog(@"Available Font Families: %@", [UIFont familyNames]);
[label setFont:[UIFont fontWithName:@"Consolas" size:20.0f]];

GraphicsServices 甚至可以在运行时加载,以防 API将来消失:

#import <dlfcn.h>
NSUInteger loadFonts()
{
    NSUInteger newFontCount = 0;
    NSBundle *frameworkBundle = [NSBundle bundleWithIdentifier:@"com.apple.GraphicsServices"];
    const char *frameworkPath = [[frameworkBundle executablePath] UTF8String];
    if (frameworkPath) {
        void *graphicsServices = dlopen(frameworkPath, RTLD_NOLOAD | RTLD_LAZY);
        if (graphicsServices) {
            BOOL (*GSFontAddFromFile)(const char *) = dlsym(graphicsServices, "GSFontAddFromFile");
            if (GSFontAddFromFile)
                for (NSString *fontFile in [[NSBundle mainBundle] pathsForResourcesOfType:@"ttf" inDirectory:nil])
                    newFontCount += GSFontAddFromFile([fontFile UTF8String]);
        }
    }
    return newFontCount;
}

edit: This answer is defunct as of iOS3.2; use UIAppFonts

The only way I've been able to successfully load custom UIFonts is via the private GraphicsServices framework.

The following will load all the .ttf fonts in the application's main bundle:

BOOL GSFontAddFromFile(const char * path);
NSUInteger loadFonts()
{
    NSUInteger newFontCount = 0;
    for (NSString *fontFile in [[NSBundle mainBundle] pathsForResourcesOfType:@"ttf" inDirectory:nil])
        newFontCount += GSFontAddFromFile([fontFile UTF8String]);
    return newFontCount;
}

Once fonts are loaded, they can be used just like the Apple-provided fonts:

NSLog(@"Available Font Families: %@", [UIFont familyNames]);
[label setFont:[UIFont fontWithName:@"Consolas" size:20.0f]];

GraphicsServices can even be loaded at runtime in case the API disappears in the future:

#import <dlfcn.h>
NSUInteger loadFonts()
{
    NSUInteger newFontCount = 0;
    NSBundle *frameworkBundle = [NSBundle bundleWithIdentifier:@"com.apple.GraphicsServices"];
    const char *frameworkPath = [[frameworkBundle executablePath] UTF8String];
    if (frameworkPath) {
        void *graphicsServices = dlopen(frameworkPath, RTLD_NOLOAD | RTLD_LAZY);
        if (graphicsServices) {
            BOOL (*GSFontAddFromFile)(const char *) = dlsym(graphicsServices, "GSFontAddFromFile");
            if (GSFontAddFromFile)
                for (NSString *fontFile in [[NSBundle mainBundle] pathsForResourcesOfType:@"ttf" inDirectory:nil])
                    newFontCount += GSFontAddFromFile([fontFile UTF8String]);
        }
    }
    return newFontCount;
}
凉城凉梦凉人心 2024-07-16 12:13:29

使用 iOS 8+ 和 Xcode 6+ 您可以轻松实现这一点。 步骤如下:

1) 将字体拖放到 Xcode Supporting Files 文件夹中。 不要忘记在添加到目标部分标记您的应用。 从这一刻起,您可以在 IB 中使用此字体并从字体托盘中选择它。

在此处输入图像描述

2) 要在您的设备中使用此字体,请打开您的 info.plist 并添加应用程序提供的字体 键。 它将包含 Item 0 键,您必须添加字体名称作为值。 字体名称可能与您的字体文件名不同。 但首先,尝试添加您的文件名,在大多数情况下这是可行的。

在此处输入图像描述

如果没有,这篇文章总是对我有帮助。

这是本文中的代码片段,可帮助您找到字体名称。

func allFonts(){

   for family in UIFont.familyNames(){

       println(family)


       for name in UIFont.fontNamesForFamilyName(family.description)
       {
           println("  \(name)")
       }

   }

}

编辑

我想提一下,您需要将字体文件添加到目标的构建阶段复制捆绑资源。 如果没有它,您将不会在设备上看到您的字体。 这可能会导致意想不到的行为。

例如,当 UITextField 具有自定义字体时,我遇到了 bug,但该字体不在复制捆绑资源中。 当我使用此 textfield 转到 viewcontroller 时,在调用 viewDidLoad 函数之前有大约 4 秒的延迟。 解决字体问题消除了这种延迟。 所以,建议检查两遍。 (rdar://20028250) 顺便说一句,我无法重现该错误,但我确信问题出在字体上。

With iOS 8+ and Xcode 6+ you can make this easily. Here are the steps:

1) Drag and drop your font to Xcode Supporting Files folder. Don't forget to mark your app at Add to targets section. From this moment you can use this font in IB and choose it from font pallet.

enter image description here

2) To make this font available to in your device, open your info.plist and add Fonts provided by application key. It will contain Item 0 key, you must add your font name as the value. Font name can vary from your font file name. But first, try to add your filename in most cases this work.

enter image description here

If not, this article always helped me.

Here is swift snippet of the code from this article to help you find your font name.

func allFonts(){

   for family in UIFont.familyNames(){

       println(family)


       for name in UIFont.fontNamesForFamilyName(family.description)
       {
           println("  \(name)")
       }

   }

}

EDIT

I want to mention, that you need to add font files to your Target's Build Phases, Copy Bundle Resources. Without it, you won't see your font on the device. And it could lead to unexpected behaviour.

For example, I encounter a bug, when UITextField have custom font, but this font wasn't in the Copy Bundle Resources. And when I segue to the viewcontroller with this textfield, there is a delay about 4 seconds before viewDidLoad function was called. Resolving font troubles removed this delay. So, recommend to check it twice. (rdar://20028250) Btw, I wasn't able to reproduce the bug, but I'm sure that problem was with the font.

惜醉颜 2024-07-16 12:13:29

我已经这样做了:

加载字体:

- (void)loadFont{
  // Get the path to our custom font and create a data provider.
  NSString *fontPath = [[NSBundle mainBundle] pathForResource:@"mycustomfont" ofType:@"ttf"]; 
  CGDataProviderRef fontDataProvider = CGDataProviderCreateWithFilename([fontPath UTF8String]);

  // Create the font with the data provider, then release the data provider.
  customFont = CGFontCreateWithDataProvider(fontDataProvider);
  CGDataProviderRelease(fontDataProvider); 
}

现在,在您的 drawRect: 中,执行如下操作:

-(void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    // Get the context.
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect);
    // Set the customFont to be the font used to draw.
    CGContextSetFont(context, customFont);

    // Set how the context draws the font, what color, how big.
    CGContextSetTextDrawingMode(context, kCGTextFillStroke);
    CGContextSetFillColorWithColor(context, self.fontColor.CGColor);
    UIColor * strokeColor = [UIColor blackColor];
    CGContextSetStrokeColorWithColor(context, strokeColor.CGColor);
    CGContextSetFontSize(context, 48.0f);

    // Create an array of Glyph's the size of text that will be drawn.
    CGGlyph textToPrint[[self.theText length]];

    // Loop through the entire length of the text.
    for (int i = 0; i < [self.theText length]; ++i) {
        // Store each letter in a Glyph and subtract the MagicNumber to get appropriate value.
        textToPrint[i] = [[self.theText uppercaseString] characterAtIndex:i] + 3 - 32;
    }
    CGAffineTransform textTransform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
    CGContextSetTextMatrix(context, textTransform);
    CGContextShowGlyphsAtPoint(context, 20, 50, textToPrint, [self.theText length]);
}

基本上,您必须对文本进行一些强力循环,并使用幻数来处理在字体中找到你的偏移量(在这里,请看我使用 29),但它有效。

另外,您必须确保字体是合法嵌入的。 大多数都不是,并且有专门从事此类事情的律师,所以请注意。

I have done this like this:

Load the font:

- (void)loadFont{
  // Get the path to our custom font and create a data provider.
  NSString *fontPath = [[NSBundle mainBundle] pathForResource:@"mycustomfont" ofType:@"ttf"]; 
  CGDataProviderRef fontDataProvider = CGDataProviderCreateWithFilename([fontPath UTF8String]);

  // Create the font with the data provider, then release the data provider.
  customFont = CGFontCreateWithDataProvider(fontDataProvider);
  CGDataProviderRelease(fontDataProvider); 
}

Now, in your drawRect:, do something like this:

-(void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    // Get the context.
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect);
    // Set the customFont to be the font used to draw.
    CGContextSetFont(context, customFont);

    // Set how the context draws the font, what color, how big.
    CGContextSetTextDrawingMode(context, kCGTextFillStroke);
    CGContextSetFillColorWithColor(context, self.fontColor.CGColor);
    UIColor * strokeColor = [UIColor blackColor];
    CGContextSetStrokeColorWithColor(context, strokeColor.CGColor);
    CGContextSetFontSize(context, 48.0f);

    // Create an array of Glyph's the size of text that will be drawn.
    CGGlyph textToPrint[[self.theText length]];

    // Loop through the entire length of the text.
    for (int i = 0; i < [self.theText length]; ++i) {
        // Store each letter in a Glyph and subtract the MagicNumber to get appropriate value.
        textToPrint[i] = [[self.theText uppercaseString] characterAtIndex:i] + 3 - 32;
    }
    CGAffineTransform textTransform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
    CGContextSetTextMatrix(context, textTransform);
    CGContextShowGlyphsAtPoint(context, 20, 50, textToPrint, [self.theText length]);
}

Basically you have to do some brute force looping through the text and futzing about with the magic number to find your offset (here, see me using 29) in the font, but it works.

Also, you have to make sure the font is legally embeddable. Most aren't and there are lawyers who specialize in this sort of thing, so be warned.

无所谓啦 2024-07-16 12:13:29

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

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

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

3)确保您拥有使用该字体的合法权利。 通过将其包含在您的应用程序中,您也可以分发它,并且您需要有权这样做。

Yes, you can include custom fonts. Refer to the documentation on UIFont, specifically, the fontWithName:size: method.

1) Make sure you include the font in your resources folder.

2) The "name" of the font is not necessarily the filename.

3) Make sure you have the legal right to use that font. By including it in your app, you're also distributing it, and you need to have the right to do that.

上课铃就是安魂曲 2024-07-16 12:13:29

如果您使用的是xcode 4.3,则必须将字体添加到Copy Bundle Resources下的Build Phase,根据线程中的 https://stackoverflow.com/users/1292829/arne自定义字体 Xcode 4.3。 这对我有用,以下是我在应用程序中使用自定义字体所采取的步骤:

  1. 将字体添加到您的项目中。 我将 OTF(或 TTF)文件拖放到我创建的新组中,并接受 xcode 将文件复制到项目文件夹的选择。
  2. 创建 UIAppFonts 数组,并将您的字体列为数组中的项目。 只是名称,而不是扩展名(例如“GothamBold”、“GothamBold-Italic”)。
  3. 单击屏幕左侧项目导航器顶部的项目名称方式。
  4. 单击 xcode 主区域中显示的 Build Phases 选项卡。
  5. 展开“复制捆绑资源”部分,然后单击“+” 添加字体。
  6. 从单击“+”时弹出的文件导航器中选择字体文件。
  7. 对您必须添加到项目的每种字体执行此操作。

If you are using xcode 4.3, you have to add the font to the Build Phase under Copy Bundle Resources, according to https://stackoverflow.com/users/1292829/arne in the thread, Custom Fonts Xcode 4.3. This worked for me, here are the steps I took for custom fonts to work in my app:

  1. 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.
  2. Create the UIAppFonts array with your fonts listed as items within the array. Just the names, not the extension (e.g. "GothamBold", "GothamBold-Italic").
  3. Click on the project name way at the top of the Project Navigator on the left side of the screen.
  4. Click on the Build Phases tab that appears in the main area of xcode.
  5. Expand the "Copy Bundle Resources" section and click on "+" to add the font.
  6. Select the font file from the file navigator that pops open when you click on the "+".
  7. Do this for every font you have to add to the project.
你的往事 2024-07-16 12:13:29

我建议您遵循我最喜欢的简短教程之一: http://codewithchris.com/common-mistakes-with-adding-custom-fonts-to-your-ios-app/ 此信息来自于此。

第 1 步 - 将 .ttf 或 .otf 从 Finder 拖入您的项目

注意 - 请务必在主应用程序目标上点击“添加到目标”框

将字体文件拖到您的项目并单击将它们添加到您的目标

如果您忘记单击将其添加到您的目标,请单击项目层次结构中的字体文件,然后在右侧面板上单击 < em>目标会员部分

如果您忘记了如何将字体添加到应用程序目标

要确保您的字体是应用程序目标的一部分,请确保它们显示在您的复制捆绑资源中在构建阶段

如何检查资源以查看字体是否是应用程序目标的一部分

第 2 步 - 将字体文件名添加到 Plist

转到 在您的 Info 部分中自定义 iOS 目标属性,并向该部分中名为 应用程序提供的字体 的项目添加一个键(您应该会看到它显示为当你输入选项时,它会将自己设置为一个数组。 单击小箭头打开数组项,然后输入您添加的 .ttf 或 .otf 文件的名称,让您的应用程序知道这些是您想要使用的字体文件

注意 - 如果您的应用程序崩溃了完成此步骤后,请检查您在此处添加的项目的拼写

添加了自定义字体的示例 plist

第 3 步 - 找出字体的名称,以便您可以

经常 调用它们您的应用程序看到的字体名称与您认为基于该字体的文件名的字体名称不同,请将其放入您的代码中并查看您的应用程序生成的日志,以查看在代码中调用什么字体名称

Swift

for family: String in UIFont.familyNames(){
  print("\(family)")
  for names: String in UIFont.fontNamesForFamilyName(family){
      print("== \(names)")
  }
}

目标 C

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

您的日志应如下所示:

搜索日志以查找字体名称的示例

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

Swift

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

目标 C

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

I would recommend following one of my favorite short tutorials here: http://codewithchris.com/common-mistakes-with-adding-custom-fonts-to-your-ios-app/ from which this information comes.

Step 1 - Drag your .ttf or .otf from Finder into your Project

NOTE - Make sure to click the box to 'Add to targets' on your main application target

Drag font files into your project and click to add them to your target

If you forgot to click to add it to your target then click on the font file in your project hierarchy and on the right side panel click the main app target in the Target Membership section

how to add fonts to app target if you forgot

To make sure your fonts are part of your app target make sure they show up in your Copy Bundle Resources in Build Phases

how to check resources to see if fonts are part of app target

Step 2 - Add the font file names to your Plist

Go to the Custom iOS Target Properties in your Info Section and add a key to the items in that section called Fonts provided by application (you should see it come up as an option as you type it and it will set itself up as an array. Click the little arrow to open up the array items and type in the names of the .ttf or .otf files that you added to let your app know that these are the font files you want available

NOTE - If your app crashes right after this step then check your spelling on the items you add here

example plist with custom fonts added

Step 3 - Find out the names of your fonts so you can call them

Quite often the font name seen by your application is different from what you think it is based on the filename for that font, put this in your code and look over the log your application makes to see what font name to call in your code

Swift

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

Your log should look something like this:

Example of searching log to find font names

Step 4 - Use your new custom font using the name from Step 3

Swift

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

Objective C

 label.font = [UIFont fontWithName:@"SourceSansPro-Regular" size:18];
∝单色的世界 2024-07-16 12:13:29

以下是如何操作的分步说明。 不需要额外的库或任何特殊的编码。

http://shang-liang.com/blog/custom-fonts-in-ios4/

大多数时候问题出在字体而不是方法上。 最好的方法是使用肯定有效的字体,例如 verdana 或 geogia。 然后更改为所需的字体。 如果不起作用,可能是字体名称不正确,或者字体不是格式良好的字体。

Here's the step by step instructions how to do it. No need extra library or any special coding.

http://shang-liang.com/blog/custom-fonts-in-ios4/

Most of the time the issue is with the font not the method. The best way to do it is to use a font that for sure will work, like verdana or geogia. Then change to the intended font. If it does not work, maybe the font name is not right, or the font is not a well formated font.

初见终念 2024-07-16 12:13:29

在现有的 iOS 应用程序上添加新字体非常容易。

您只需将字体(例如 font.ttf)添加到资源文件夹中即可。

打开您的应用程序 info.plist。 添加新行作为“应用程序提供的字体”,然后键入字体名称 font.ttf。

设置字体时,如setFont:"对应字体名称"

可以通过NSArray *check = [UIFont familyNames];来检查您的字体是否添加。

它返回您的应用程序支持的所有字体。

It is very easy to add a new font on your existing iOS App.

You just need to add the font e.g. font.ttf into your Resource Folder.

Open your application info.plist. Add a new row as "Fonts provided by application" and type the font name as font.ttf.

And when setting the font do as setFont:"corresponding Font Name"

You can check whether your font is added or not by NSArray *check = [UIFont familyNames];.

It returns all the font your application support.

演多会厌 2024-07-16 12:13:29

在查找器和“获取信息”中找到 TTF。 在“全名:”标题下,它给了我一个名称,然后将其与 fontWithName 一起使用(我只是复制并粘贴了确切的名称,在本例中不需要“.ttf”扩展名)。

Find the TTF in finder and "Get Info". Under the heading "Full name:" it gave me a name which I then used with fontWithName (I just copied and pasted the exact name, in this case no '.ttf' extension was necessary).

就像说晚安 2024-07-16 12:13:29

它还没有发布,但下一版本的 cocos2d(2d 游戏框架)将支持可变长度位图字体作为字符映射。

http://code.google.com/p/cocos2d-iphone /issues/detail?id=317

作者没有确定此版本的发布日期,但我确实看到一个帖子表明它将在未来一两个月内发布。

It's not out yet, but the next version of cocos2d (2d game framework) will support variable length bitmap fonts as character maps.

http://code.google.com/p/cocos2d-iphone/issues/detail?id=317

The author doesn't have a nailed down release date for this version, but I did see a posting that indicated it would be in the next month or two.

烟沫凡尘 2024-07-16 12:13:29

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

One important notice: You should use the "PostScript name" associated with the font, not its Full name or Family name. This name can often be different from the normal name of the font.

杀手六號 2024-07-16 12:13:29

按照此步骤操作

1) 在项目中复制您的字体

2) 在源代码模式下打开您的 .plist 文件...(注意 - 不要打开 info.plist

3)在此之前 - 右键单击​​您的字体并在 fontforge 或类似编辑器中打开它并在您的系统中安装它,它应该是安装

4)输入此

 <key>UIAppFonts</key>
<array>
    <string>MyriadPro.otf</string>
</array>

代码 5)输入此代码在您的 class .m

 [lblPoints setFont:[UIFont fontWithName:@"Myriad Pro" size:15.0]];

,lblPoints 将在您的 UILabel 完成后更改


如果您的字体仍然无法使用,请先检查您的字体兼容性

follow this step

1)Copy your font in your project

2)open your .plist file in source code mode...(Note- Dont open info.plist)

3)Before that - Right click on your font and open it in fontforge or similar editor and install it in your system ,It should be install

4)Type this

 <key>UIAppFonts</key>
<array>
    <string>MyriadPro.otf</string>
</array>

5)Type this code in your class .m

 [lblPoints setFont:[UIFont fontWithName:@"Myriad Pro" size:15.0]];

Here lblPoints will be change as of your UILabel

Done!!
If still your font not work,check your fonts compatibility first

野心澎湃 2024-07-16 12:13:29

也许作者忘记给字体指定一个 Mac FOND 名称

  1. FontForge 中打开字体,然后转到 Element>Font Info
  2. 有一个“Mac”选项,您可以在其中设置喜欢的名字。
  3. 在“文件”>“导出字体”下,您可以创建一个新的 ttf

您也可以尝试导出对话框中的“Apple”选项。

免责声明:我不是 iPhone 开发者!

Maybe the author forgot to give the font a Mac FOND name?

  1. Open the font in FontForge then go to Element>Font Info
  2. There is a "Mac" Option where you can set the FOND name.
  3. Under File>Export Font you can create a new ttf

You could also give the "Apple" option in the export dialog a try.

DISCLAIMER: I'm not a IPhone developer!

音盲 2024-07-16 12:13:29

我一直在 iOS 3.1.2 上尝试此页面上的各种建议,这些是我的结论:

简单地使用 [UIFont fontWithName:size:] 与 Resources 目录中的字体是行不通的,即使如果 FOND 名称是使用 FontForge 设置的。

如果首先使用 GSFontAddFromFile 加载字体,[UIFont fontWithName:size:] 将起作用。 但 GSFontAddFromFile 不是 iOS 3.1.2 的一部分,因此必须按照 @rpetrich 的描述动态加载。

I have been trying out the various suggestions on this page on iOS 3.1.2 and these are my conclusions:

Simply using [UIFont fontWithName:size:] with the fonts in the Resources directory will not work, even if the FOND name is set using FontForge.

[UIFont fontWithName:size:] will work if the fonts are loaded first using GSFontAddFromFile. But GSFontAddFromFile is not part of iOS 3.1.2 so it has to be dynamically loaded as described by @rpetrich.

寄居者 2024-07-16 12:13:29

查找 ATSApplicationFontsPath

一个简单的 plist 条目,允许您将字体文件包含在应用程序资源文件夹中,并且它们在您的应用程序中“正常工作”。

Look up ATSApplicationFontsPath

A simple plist entry that allows you to include the font file(s) in your app resources folder and they "just work" in your app.

心奴独伤 2024-07-16 12:13:29

我已将此页面上的一些建议合并为适用于我的 iOS 5 的内容。

首先,您必须将自定义字体添加到您的项目中。 然后,您需要遵循@iPhoneDev 的建议并将字体添加到您的 info.plist 文件中。

完成此操作后,效果如下:

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

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

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

I've combined some of the advice on this page into something that works for me on iOS 5.

First, you have to add the custom font to your project. Then, you need to follow the advice of @iPhoneDev and add the font to your info.plist file.

After you do that, this works:

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

However, you need to know the Postscript name of your font. Just follow @Daniel Wood's advice and press command-i while you're in FontBook.

Then, enjoy your custom font.

呆头 2024-07-16 12:13:29

首先将 .odt 格式的字体添加到您的资源中,在本例中我们将使用 DINEngschriftStd.otf,然后使用此代码将字体分配给标签

[theUILabel setFont:[UIFont fontWithName:@"DINEngschriftStd" size:21]];

要确保您的字体已加载到项目上,只需

NSLog(@"Available Font Families: %@", [UIFont familyNames]);

在 .plist 上 调用必须声明字体。 只需添加“应用程序提供的字体”记录并添加带有字体名称的项目 0 字符串 (DINEngschriftStd.otf)

First add the font in .odt format to your resources, in this case we will use DINEngschriftStd.otf, then use this code to assign the font to the label

[theUILabel setFont:[UIFont fontWithName:@"DINEngschriftStd" size:21]];

To make sure your font is loaded on the project just call

NSLog(@"Available Font Families: %@", [UIFont familyNames]);

On the .plist you must declare the font. Just add a 'Fonts provided by application' record and add a item 0 string with the name of the font (DINEngschriftStd.otf)

仙气飘飘 2024-07-16 12:13:29

对于 iOS 3.2 及以上版本:
使用上面几个提供的方法,它们是:

  1. 将您的字体文件(例如,Chalkduster.ttf)添加到 XCode 中项目的 Resources 文件夹中。
  2. 打开 info.plist 并添加一个名为 UIAppFonts 的新键。 该键的类型应该是数组。
  3. 将您的自定义字体名称添加到此数组,包括扩展名(“Chalkduster.ttf”)。
  4. 在您的应用程序中使用[UIFont fontWithName:@"Real Font Name" size:16]

但是
“真实字体名称”并不总是您在 Fontbook 中看到的名称。 最好的方法是询问您的设备看到了哪些字体以及确切的名称是什么。

我使用发布在以下位置的 uifont-name-grabber:
uifont-name-grabber

只需将你想要的字体放入 xcode 项目中即可,将文件名添加到其 plist 中,并在您正在构建的设备上运行它,它将使用 UIFont fontWithName: 所需的名称通过电子邮件向您发送完整的字体列表。

For iOS 3.2 and above:
Use the methods provided by several above, which are:

  1. Add your font file (for example, Chalkduster.ttf) to Resources folder of the project in XCode.
  2. Open info.plist and add a new key called UIAppFonts. The type of this key should be array.
  3. Add your custom font name to this array including extension ("Chalkduster.ttf").
  4. Use [UIFont fontWithName:@"Real Font Name" size:16] in your application.

BUT
The "Real Font Name" is not always the one you see in Fontbook. The best way is to ask your device which fonts it sees and what the exact names are.

I use the uifont-name-grabber posted at:
uifont-name-grabber

Just drop the fonts you want into the xcode project, add the file name to its plist, and run it on the device you are building for, it will email you a complete font list using the names that UIFont fontWithName: expects.

原野 2024-07-16 12:13:29

更好的解决方案是将新属性“应用程序提供的字体”添加到您的 info.plist 文件中。

然后,您可以像普通 UIFont 一样使用自定义字体。

Better solution is to add a new property "Fonts provided by application" to your info.plist file.

Then, you can use your custom font like normal UIFont.

时光匆匆的小流年 2024-07-16 12:13:29

从 iOS 4.1 开始,有一种使用自定义字体的新方法。 它允许您动态加载字体,无论是应用程序附带的文件、下载的数据还是您拥有的字体。 它还允许您根据需要加载字体,而旧方法会在应用程序启动时加载所有字体,如果您有很多字体,这可能会花费很长时间。

新方法的描述见 ios-dynamic-font-loading

您使用CTFontManagerRegisterGraphicsFont函数,为其提供一个包含字体数据的缓冲区。 然后它可用于 UIFont 和 Web 视图,就像旧方法一样。 这是该链接中的示例代码:

NSData *inData = /* your font-file data */;
CFErrorRef error;
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)inData);
CGFontRef font = CGFontCreateWithDataProvider(provider);
if (! CTFontManagerRegisterGraphicsFont(font, &error)) {
    CFStringRef errorDescription = CFErrorCopyDescription(error)
    NSLog(@"Failed to load font: %@", errorDescription);
    CFRelease(errorDescription);
}
CFRelease(font);
CFRelease(provider);

There is a new way to use custom fonts, starting with iOS 4.1. It allows you to load fonts dynamically, be they from files included with the app, downloaded data, or what have you. It also lets you load fonts as you need them, whereas the old method loads them all at app startup time, which can take too long if you have many fonts.

The new method is described at ios-dynamic-font-loading

You use the CTFontManagerRegisterGraphicsFont function, giving it a buffer with your font data. It's then available to UIFont and web views, just as with the old method. Here's the sample code from that link:

NSData *inData = /* your font-file data */;
CFErrorRef error;
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)inData);
CGFontRef font = CGFontCreateWithDataProvider(provider);
if (! CTFontManagerRegisterGraphicsFont(font, &error)) {
    CFStringRef errorDescription = CFErrorCopyDescription(error)
    NSLog(@"Failed to load font: %@", errorDescription);
    CFRelease(errorDescription);
}
CFRelease(font);
CFRelease(provider);
淡写薰衣草的香 2024-07-16 12:13:29

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)

Swift, code way: (works also with swift 2.0)

Add the required fonts to your project (just like adding images, just drag to Xcode), make sure that they are targeted to your project

add this method and load custom fonts (recommended in 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: "")
    }

}

Use example:

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

Use the font:

UIFont(name: "My-Font", size: 16.5)
北音执念 2024-07-16 12:13:29

您可以在资源文件夹中添加所需的“FONT”文件。 然后转到项目 Info.plist 文件并使用键“应用程序提供的字体”和值“字体名称”。

然后就可以调用方法[UIFont fontwithName:@"FONT NAME" size:12];

You can add the required "FONT" files within the resources folder. Then go to the Project Info.plist file and use the KEY "Fonts provided by the application" and value as "FONT NAME".

Then you can call the method [UIFont fontwithName:@"FONT NAME" size:12];

一口甜 2024-07-16 12:13:29

我做了一切可能的事情,但新字体没有出现,所以我找到了解决方案:

当您拖动 fot 文件(otf 或 ttf)时,不要忘记选中“添加到目标”下的复选框。

完成此操作后,您的字体就会出现,一切都会正常工作。

I made everything possible but the new fonts dont appear so I found the solution:

When you drag the fot files(otf or ttf) DONT forget to check the checkbox under "Add to targets".

After doing that your font will appear and everything will work fine.

柠檬色的秋千 2024-07-16 12:13:29

尽管上面的一些答案是正确的,但我已经为仍然遇到字体问题的人们编写了详细的视觉教程。

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

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

是正确的。 现在请使用任何其他黑客方式。 如果您在查找字体名称并添加它们时仍然遇到问题,请参阅以下教程 -

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

Although some of the answers above are correct, I have written a detailed visual tutorial for people still having problems with fonts.

The solutions above which tell you to add the font to the plist and use

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

are the correct ones. Please do now use any other hackish way. If you are still facing problems with finding font names and adding them, here is the tutorial -

Using custom fonts in ios application

脸赞 2024-07-16 12:13:29

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

是的,您可以按照以下步骤

:将自定义字体文件添加到支持文件中的项目中

将一个密钥添加到名为 UIAppFonts 的 Info.plist 文件中。

将此键设置为数组

对于您拥有的每种字体,将字体文件的完整名称(包括扩展名)作为 UIAppFonts 数组的项目输入

Save Info.plist 现在,在您的应用程序中,您可以简单地调用 [UIFont fontWithName:@"your Custom font Name" size:20] 获取与 UILabels 一起使用的自定义字体
应用此后,如果您没有获得正确的字体,则双击自定义字体,仔细查看顶部字体名称正在输入,然后复制此字体,粘贴到此处 [UIFont fontWithName:@" 这里过去您的自定义字体名称" 大小: 20]

我希望你能得到正确的答案

yes you can use custom font in your application

step by step following there:

Add your custom font files into your project in supporting files

Add a key to your Info.plist file called UIAppFonts.

Make this key an array

For each font you have, enter the full name of your font file (including the extension) as items to the UIAppFonts array

Save Info.plist Now in your application you can simply call [UIFont fontWithName:@"your Custom font Name" size:20] to get the custom font to use with your UILabels
after applying this if your not getting correct font then you double click on the custom font , and see carefully top side font name is comming and copy this font , paste, here [UIFont fontWithName:@" here past your Custom font Name" size:20]

i hope you will get correct answer

╭⌒浅淡时光〆 2024-07-16 12:13:29

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

是的,您可以按照以下步骤

  • :将自定义字体文件添加到支持文件中的项目中。
  • 将一个密钥添加到名为 UIAppFonts 的 Info.plist 文件中。
  • 将此键设为数组
  • 对于您拥有的每种字体,输入字体文件的全名(包括扩展名)作为 UIAppFonts 数组的项目
  • 保存 Info.plist
    获取与您的 UILabels 一起使用的自定义字体

现在,在您的应用程序中,您只需调用 [UIFont fontWithName:@"your Custom font Name" size:20] 即可在应用此命令后 如果你没有得到正确的字体
然后双击自定义字体,仔细观察顶部字体名称即将出现
并复制此字体,粘贴到此处[UIFont fontWithName:@"此处超过您的自定义字体名称"size:20]
我希望你能得到正确的答案

yes you can use custom font in your application

step by step following there:

  • Add your custom font files into your project in supporting files
  • Add a key to your Info.plist file called UIAppFonts.
  • Make this key an array
  • For each font you have, enter the full name of your font file (including the extension) as items to the UIAppFonts array
  • Save Info.plist
    Now in your application you can simply call [UIFont fontWithName:@"your Custom font Name" size:20] to get the custom font to use with your UILabels

after applying this if your not getting correct font
then you double click on the custom font , and see carefully top side font name is comming
and copy this font , paste, here [UIFont fontWithName:@" here past your Custom font Name" size:20]
i hope you will get correct answer

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文