Apple Swift Logo

UIFont not responding or nil

My font does not respond and it says nil when I print it? What’s happening here?
Actually, if your UIFont happens to be nil, it’s maybe because you’re not calling it properly! Haha, very funny, I know, but let’s have a look at happened to me recently.

Here is what I did:
I imported "MyFont-Regular.ttf" and "MyFont-bold.ttf" in Xcode.
I set the constants with the font name.

let fontRegular = "MyFont-Regular"
let fontBold = "MyFont-Bold"

And I set the font to that label in the view:

label.font = UIFont(name: fontRegular, size: 12.0)

and … nothing happened, well, the label was displayed but not as wanted. I expected something like label2 and label1 happened. And Label3 worked just fine btw…

UIFont Labels example
Label 1, 2 and 3… fail, expected and success

I printed the UIFont and it failed on that line! So I double checked if my fonts were loaded correctly. And they were, so the problem was somewhere else.

Then I remembered I saw something about printing the available fonts in this article: Custom Fonts in Swift.

Those few lines can save you a lot of time and trouble:

func printMyFonts() {
    print("--------- Available Font names ----------")

    for name in UIFont.familyNames() {
        print(name)
        if let nameString = name as? String {
            print(UIFont.fontNamesForFamilyName(nameString))
        }
    }
}

After running the little PrintMyFonts() function, I realized that the font I needed was called "MyFont" by the system and not "MyFont-Regular". Aha!

Facepalm

That sounds maybe trivial, but I hope this will help you avoiding headaches and pants-over-head frustration. And remember: do not assume the font name based on the file name, even if it works sometimes ;)

Bonus: the list of default fonts supported on iOS: iOSFonts.com. It lists every font for every iOS version, for iPhone, iPad and Watch, pretty neat!

Leave a Comment

You want to leave a comment? Sweet! Please do so, but keep in mind that all comments are moderated and rel="nofollow" is in use. So no fake comment or advertisement will be approved. And don't worry, your email address won't be published. Thanks!

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>