ios - Swift 自定义字体 Xcode

标签 ios xcode swift fonts

我正在使用 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)

最佳答案

这些是将自定义字体添加到您的应用程序的步骤:

  1. 在您的应用程序中添加“gameOver.ttf”字体 (Make sure that it's included in the target)
  2. 修改application-info.plist文件。
  3. 在新行中添加关键字“应用程序提供的字体”
  4. 并将“gameOver.ttf”添加为数组“应用程序提供的字体”中的新项目。

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

There are 2 ways to find the name:

  1. Install the font on your Mac. Open Font Book, open the font and see what name is listed.
  2. Programmatically list the available fonts in your app

对于第二种方法,添加这一行是您的应用委托(delegate)的 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 

Useful resource

关于ios - Swift 自定义字体 Xcode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31420758/

相关文章:

ios - 标签显示超出我的自定义 TableViewCell 范围并通过 swift 设置自动布局

objective-c - 在 Objective-C(测试)代码中导入框架的 Swift 类

ios - SKPSMTP消息库

ios - Google Places - 当前位置抛出 : An internal error occurred in the Places API library

swift - 设备方向更改后使 collectionViewCell 中的 CAShapeLayer 无效并重绘

ios - 横向 iPhone 6 Plus 的 UIModalPresentationPopover 不显示弹出窗口

android - 对于有这么多数据的东西,JSON 比 XML 好吗 "classification"

string - Swift 和 Firebase |使用 textField 获取一段数据并使用该数据查询 firebase

iOS:如何创建一行相同百分比宽度的控件

ios - Xcode 6.3 : Could not load NIB in bundle