How to add custom fonts to a Swift/SwiftUI app

How to add custom fonts to a Swift/SwiftUI app

# Download the font you want.

Go to Google Fonts, and download the font you want. In this tutorial, I'm going to use DM Serif Display. You don't have to use Google Fonts though. You can use any fonts you want, make sure you have the right license.

# Prepare the folder and files inside XCode

Create a folder called "Fonts" inside your XCode, and copy & paste the unpacked fonts there. In this case, it just has 2 fonts.

Go to your Project Settings > Info > Click the little "+" icon to add more variable

Search and choose for "Fonts provided by application" option

CMD + C and CMD + V the file inside the row, to copy and paste your font into the XCode

# Code the Font extension

Great! our initial setup is finished. Now we are ready to write some code. Create a new folder called DesignSystem (You can call it anything, this is just my convention). And a new Swift file called Font+Ext.swift (Because it's an Extension) inside it

import Foundation
import SwiftUI

// Create an Extension of Font class
extension Font {
    // Define a static method called "DMSerifDisplay" 
    // that takes 1 argument called "fontSize"
    // return custom Font instance using "DMSerifDisplay-Regular.ttf"
    static func DMSerifDisplay(fontSize: CGFloat) -> Font {
        return .custom("DMSerifDisplay-Regular", size: fontSize)
    }
    // Same as above, only this time is the Italic version
    static func DMSerifDisplayItalic(fontSize: CGFloat) -> Font {
        return .custom("DMSerifDisplay-Italic", size: fontSize)
    }
}

Now let's try our new shiny font. Create a new SwiftUI file, and add this code

import SwiftUI

struct SplashScreen: View {
    var body: some View {
        Text("Hello world")
            // Use the new Font by calling its 
            // Function (DMSerifDisplay)
            .font(.DMSerifDisplay(fontSize: 54))

        Text("As comparison, this is the original font")
    }
}

#Preview {
    SplashScreen()
}

# Done!

Now you can treat the new font like the original Font. Like adding weight, sizes, color, etc. As long as you added/provided the font files (Bold, Light, etc.).