且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift自定义字体Xcode

更新时间:2021-10-01 09:28:28

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

These are the steps to add a custom font to you application:

  1. 在应用程序中添加"gameOver.ttf"字体(确保已将其包含在目标中)
  2. 修改application-info.plist文件.
  3. 在新行中添加键应用程序提供的字体"
  4. 并在数组应用程序提供的字体" 中将"gameOver.ttf"添加为新项.
  1. Add "gameOver.ttf" font in your application ( Make sure that it's included in the target)
  2. Modify the application-info.plist file.
  3. Add the key "Fonts provided by application" in a new row
  4. and add "gameOver.ttf" as new item in the Array "Fonts provided by application".

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

Now the font will be available in Interface Builder. To use the custom font in code we need to refer to it by name, but the name often isn’t the same as the font’s filename

有两种查找名称的方法:

There are 2 ways to find the name:

  1. 在Mac上安装字体.打开字体书,打开字体,然后查看 列出了什么名字.
  2. 以编程方式列出您应用中的可用字体
  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

对于第二种方法,添加此行是您的应用程序代表的didFinishLaunchingWithOptions

for the second approach add this line is your app delegate’s didFinishLaunchingWithOptions

print(UIFont.familyNames)

要列出每个字体家族中包含的字体,在Swift 5中:

To list the fonts included in each font family, in Swift 5:

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

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

after finding the name of your custom font you may use it like this:

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

或在简单标签中:

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

有用的资源