askvity

Setting Up Your Custom Fonts

Published in Swift Custom Fonts 6 mins read

To use custom fonts in Swift, you need to follow a straightforward process involving adding the font files to your Xcode project, registering them in your Info.plist file, and then applying them to your UI elements in code. This allows you to personalize your app's typography beyond the system's default offerings.

The initial setup involves preparing your font files and integrating them into your Xcode project.

Step 1: Acquire Your Fonts

First, you need to choose the font that you like and download it. Custom fonts typically come in TrueType Font (.ttf) or OpenType Font (.otf) formats. You can find free or paid fonts from various online sources such as Google Fonts, Font Squirrel, Adobe Fonts, or MyFonts.

Step 2: Add Fonts to Your Xcode Project

Once you have your font file(s) ready:

  1. Drag and Drop: Locate your downloaded font files (e.g., MyCustomFont-Regular.ttf, MyCustomFont-Bold.otf).
  2. Integrate: Drag these files directly into your Xcode project's Navigator. You can organize them within a new group (folder) if you prefer, for better project structure.
  3. Configuration Prompt: When you drag them, Xcode will present a dialog box. Make sure to check "Copy items if needed" to ensure the font files are copied into your project directory, making them part of your app bundle.
  4. Target Membership: Crucially, ensure that your app's target is checked under "Add to targets." This step links the font files to your specific application build, making them accessible at runtime.

![Xcode Add Files Dialog Example - Placeholder for visual aid if available]

Registering Fonts in Your Project's Info.plist

After adding the font files to your project, you must inform iOS that your application intends to use these custom fonts. This is done by listing them in your project's Info.plist file.

  1. Open Info.plist: In your Xcode project Navigator, click on your project, then select your target under "TARGETS." Go to the "Info" tab.
  2. Add New Row: Hover over any existing row and click the "+" button that appears to add a new entry.
  3. Select "Fonts provided by application": From the dropdown list of keys, select Fonts provided by application (or UIAppFonts if you prefer to edit as source code).
  4. List Font Files: Xcode will create an array. For each font file you added to your project, click the "+" button next to Item 0 (or subsequent items) and enter the exact filename of your font, including its extension (e.g., MyCustomFont-Regular.ttf).

Example Info.plist Entry:

Key Type Value (Example)
Fonts provided by application Array
↳ Item 0 String MyCustomFont-Regular.ttf
↳ Item 1 String MyCustomFont-Bold.otf

Using Custom Fonts in Your Swift Code

Once your fonts are added to the project and registered in Info.plist, you can apply them to your UI elements using the UIFont class.

Verify Font Names

It's common for the actual font name (the name used in UIFont calls) to differ from the font's filename. To find the exact font name that iOS recognizes, you can print a list of all available font names in your app, including your custom ones:

import UIKit

func printAllFonts() {
    for familyName in UIFont.familyNames.sorted() {
        print("Family Name: \(familyName)")
        for fontName in UIFont.fontNames(forFamilyName: familyName).sorted() {
            print("  Font Name: \(fontName)")
        }
    }
}

// Call this function early in your app lifecycle, e.g., in AppDelegate's didFinishLaunchingWithOptions
// printAllFonts()

Run your app, check the console output, and look for your custom font's family and font names. For instance, a file named MyCustomFont-Regular.ttf might appear as MyCustomFont-Regular or MyCustomFont with a Regular style.

Applying Fonts to UI Elements

With the correct font name identified, you can apply it programmatically.

For UILabel:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let customLabel = UILabel()
        customLabel.text = "Hello, Custom Font!"
        customLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(customLabel)

        // Set the custom font and size
        if let customFont = UIFont(name: "MyCustomFont-Regular", size: 24) {
            customLabel.font = customFont
        } else {
            print("Error: Could not load 'MyCustomFont-Regular' font.")
        }

        // Layout constraints (example)
        NSLayoutConstraint.activate([
            customLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            customLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }
}

For UIButton:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let customButton = UIButton(type: .system)
        customButton.setTitle("Tap Me!", for: .normal)
        customButton.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(customButton)

        // Set the custom font for the button's title label
        if let customFont = UIFont(name: "MyCustomFont-Bold", size: 20) {
            customButton.titleLabel?.font = customFont
        } else {
            print("Error: Could not load 'MyCustomFont-Bold' font.")
        }

        // Layout constraints (example)
        NSLayoutConstraint.activate([
            customButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50),
            customButton.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        ])
    }
}

Using Custom Fonts in Interface Builder (Optional)

After successfully adding and registering your fonts, they should appear in the Font Inspector within Interface Builder (Storyboards or XIBs) under the "Custom" section. You can then select your desired custom font directly from the dropdown menus for elements like UILabel, UITextField, and UITextView. However, for robust font management and dynamic sizing, programmatic setup is often preferred.

Troubleshooting Common Issues

  • Incorrect Font Name: The most common issue. Double-check the exact font name using the printAllFonts() function.
  • Missing Info.plist Entry: Ensure Fonts provided by application is correctly added, and all font filenames (with extensions) are listed.
  • Target Membership: Verify that the font files are included in your app's target under "Build Phases" -> "Copy Bundle Resources."
  • Caching Issues: Sometimes, Xcode or iOS caches font information. Clean your build folder (Product > Clean Build Folder) and restart Xcode if issues persist.

By following these steps, you can successfully integrate and utilize custom fonts, significantly enhancing your Swift application's visual appeal and brand identity.

Related Articles