Skip to content
DeveloperMemos

How to Use a Custom Font in a SwiftUI App

SwiftUI, Custom Font, Xcode2 min read

To include a custom font in your SwiftUI project, you must ensure that the font file is added to your Xcode project. This typically involves importing the font file into your project directory and ensuring it's included in the app's resources.

Adding Custom Fonts to Your Project

The first step in using a custom font is to add the font file to your Xcode project. To do this, follow these steps:

  1. Locate or Obtain the Font File: If you don't have a custom font already, there are various resources online where you can obtain commercial or open-source fonts. Once obtained, ensure that the font file is in a compatible format such as .ttf or .otf.

  2. Add the Font File to Your Xcode Project: In Xcode, navigate to the Project Navigator and right-click on the folder where you want to add the font. Select "Add Files to [Your Project]" and choose the font file you want to include. Ensure that the font file is included in the app's target when prompted.

  3. Verify Inclusion: After adding the font file, double-check that it appears under the "Copy Bundle Resources" section of your app's target settings to ensure it will be packaged with your app.

  4. Add it to Info.plist: After you've added the file you'll need to add it to your Info.plist file for it to work properly. Add the "Fonts provided by application" key, which is an Array. Inside this Array add a new String item which will be your font name. Make sure you also add the extension of the font so for example "MyFont.ttf".

Declaring and Using Custom Fonts in SwiftUI

Once the custom font file is added to your Xcode project, you can start using it within your SwiftUI views. Here's a simple example of how you can declare and use a custom font:

1import SwiftUI
2
3struct CustomFontView: View {
4 var body: some View {
5 Text("Hello, Custom Font!")
6 .font(.custom("YourCustomFontName", size: 24))
7 }
8}

In the above code snippet, .custom is used to specify the name of the custom font and its size. Replace "YourCustomFontName" with the actual name of the custom font you added to your project.

Applying Custom Fonts Globally

To apply a custom font globally throughout your SwiftUI app, you can leverage the environment modifier. This allows you to set the default font for all text elements within the app. Here's an example of how to accomplish this:

1import SwiftUI
2
3@main
4struct CustomFontApp: App {
5 var body: some Scene {
6 WindowGroup {
7 ContentView()
8 .environment(\.font, Font.custom("YourCustomFontName", size: 16))
9 }
10 }
11}

By setting the environment font using .environment(\.font, ...), you ensure that the specified custom font is applied as the default font for all text elements within the app.