Custom Fonts not showing on font family list

Viewed 828

I'm using Swift 5 and Xcode 11.4.1 on macOS Catalina.

I have had no problem applying custom font til today. I'm trying to apply custom font to a label called "textLabel". Let me show you how I tried first and then please tell me what is wrong.

  • By Using Storyboard
  • I want to use custom font whose name is "myFont.ttf" to a label called "textLabel".
  • I dropped the font file in Xcode with this option. Option Screenshot
  • I went to info.plist to let Xcode know that I provide custom font. info.plist screenshot
  • I opened the main.storyboard, went to attribute inspectors and chose the label's font as custom style.
  • I can't find "myFont" font in the font family list. << The problem here.

So I tried another way, programmatically.

  • By Using Code
  1. Same process as mentioned above until the number 3.
  2. I wrote this code inside of viewController.swift file.
import UIKit

class ViewController: UIViewController {
    
  @IBOutlet weak var textLabel: UILabel!
   
  override func viewDidLoad() {
    super.viewDidLoad()
        
    textLabel.font = UIFont(name: "myFont.ttf", size: 22)
  }
}
  1. I ran the app, It shows just normal system font.

I tried both ways over and over (even I created new files for 5 times to just test this font thing)and also I tried with various fonts but same thing happened.

1 Answers

The issue is with the name you're providing for UIFont in the declaration UIFont(name: "myFont.ttf", size: 22). You're not supposed to provide the name myFont instead you're supposed to provide the actual name of the font eg: Avalon. You can get the font by listing out the entire list of fonts you have. Like this:

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

Now check the console output, look for your new font's 'family' and 'font' name. Pass whatever is displayed as the 'font' name corresponding to your new font family (there could be more than one 'font' associated with your new font 'family') to let myNewFont = UIFont(name: "font_name_from_console_output", size: 22) and you should be in business!

Related