Swift自定义字体Xcode

39

我正在使用Swift在Xcode(版本7.0 Beta)中创建游戏,并希望在游戏结束时以“gameOver.ttf”字体显示标签“Game Over”。我已将字体添加到我的资源文件夹中,但不知道如何在代码中引用它。能请教一下吗? 我的代码:

let label = SKLabelNode(fontNamed: "gameOver")
    label.text = "Game Over"
    label.fontColor = SKColor.redColor()
    label.fontSize = 150
    label.position = CGPointMake(0, 100)
    label.horizontalAlignmentMode = .Center
    node.addChild(label)

5个回答

103

以下是将自定义字体添加到应用程序的步骤:

  1. 将 "gameOver.ttf" 字体添加到您的应用程序中(确保它已包含在目标中)。
  2. 修改应用程序信息属性列表文件。
  3. 在新行中添加键 "Fonts provided by application"
  4. 并将 "gameOver.ttf" 添加为 Array "Fonts provided by application" 的新项。

现在该字体将在 Interface Builder 中可用。 要在代码中使用自定义字体,我们需要通过名称引用它,但名称通常与字体文件名不同。

有两种方法可以找到名称:

  1. 在 Mac 上安装字体。打开 Font Book,打开字体并查看列出的名称。
  2. 以编程方式列出应用程序中可用的字体

对于第二种方法,在您的应用程序委托的 didFinishLaunchingWithOptions 添加此行:

print(UIFont.familyNames)

要在Swift 5中列出每个字体系列中包含的字体,请使用以下方法:

 func printFonts() {
    for familyName in UIFont.familyNames {
        print("\n-- \(familyName) \n")
        for fontName in UIFont.fontNames(forFamilyName: familyName) {
            print(fontName)
        }
    }
}

找到您自定义字体的名称后,您可以像这样使用它:

SKLabelNode(fontNamed: "gameOver") // put here the correct font name

或者用一个简单的标签:

cell.textLabel?.font = UIFont(name: "gameOver", size: 16) // put here the correct font name 

有用资源


哦我的天啊..那就是我缺失的链接 - 我没有将自定义字体添加到Info.plist中。谢谢你!你让我的一天都变得美好了! - marika.daboja

6

Swift 4和5。我已经为应用程序字体创建了一个枚举。首先通过双击所需字体进行系统安装。然后,安装的字体将出现在Attribute inspector中的Custom fonts下。

进入图片描述此处

import Foundation
import UIKit

private let familyName = "Montserrat"

enum AppFont: String {
    case light = "Light"
    case regular = "Regular"
    case bold = "Bold"

    func size(_ size: CGFloat) -> UIFont {
        if let font = UIFont(name: fullFontName, size: size + 1.0) {
            return font
        }
        fatalError("Font '\(fullFontName)' does not exist.")
    }
    fileprivate var fullFontName: String {
        return rawValue.isEmpty ? familyName : familyName + "-" + rawValue
    }
}

使用

self.titleLabel?.font = AppFont.regular.size(12.0)

1

除了上面的答案,我想再添加一个关于如何在Xcode中安装自定义字体的答案,这样可以在Mac和MAC上访问。

1. 从这里选择并下载您喜欢的字体样式

2. Unzip the download folder and select all the fonts from folder and double tap to open

3. Pop up appears to select all the fonts > check all and install

4. Open Xcode, one can see from Attribute inspector for selected label

就这些 :)

请注意附图获取更多参考:

enter image description here

字体Lato出现在Xcode工作区

enter image description here


0

如果您需要将其添加到应用程序中,还必须关闭XCode并重新打开它,以便在将字体添加到info.plist后,新添加的字体可以显示在字体下拉菜单中。

请在官方文档中查看此处:https://developer.apple.com/documentation/uikit/text_display_and_fonts/adding_a_custom_font_to_your_app


0
解决我的问题的方法是:
即使你将.ttf字体文件放在子目录中,在Info.plist文件中,确保只引用文件名为"filename.ttf",不要在文件路径中添加子目录名称,比如"subdirectory/filename.ttf"。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接