Your app looks great with that custom font, but does it support dynamic font sizes for the users that need it?
Before we get started, please take a couple of seconds to follow me and đź‘Ź clap for the article so that we can help more people learn about this useful content.
Jumping into the code
If you don’t already have a custom font in your project, Apple already has some great docs on that process here: https://developer.apple.com/documentation/swiftui/applying-custom-fonts-to-text. For our tutorial, we will be using the Roboto font from Google Fonts.
The code that we need is actually mentioned in the docs from Apple, but I wanted to call it out here since the topic of this tutorial is specifically making your custom font more accessible. The relativeTo parameter is what gives the custom font the ability to automatically scale with the size of the users preferred font size. While this works, we don’t want to have to use this long string of text every time we want to use our custom font, let’s see if we can make this a little cleaner.
// ContentView.swift
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, Great World!")
Text("Hello, Great World!")
.font(Font.custom("RobotoRegular", size: 18, relativeTo: .body))
}
.padding()
}
}
#Preview {
ContentView()
}
By breaking our custom font out into its own class, and specifying the type of font, we can make our class easily extendable to hold the various font sizes and weights all while making our call sites cleaner and type safe.
// ContentView.swift
import SwiftUI
class CustomFont {
static let body = Font.custom("RobotoRegular", size: 18, relativeTo: .body)
}
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, Great World!")
Text("Hello, Great World!")
.font(CustomFont.body)
}
.padding()
}
}
#Preview {
ContentView()
}
If you got value from this article, please consider following me, đź‘Ź clapping for this article, or sharing it to help others more easily find it.
If you have any questions on the topic or know of another way to accomplish the same task, feel free to respond to the post or share it with a friend and get their opinion on it. If you want to learn more about native mobile development, you can check out the other articles I have written here: https://medium.com/@jpmtech. If you want to see apps that have been built with native mobile development, you can check out my apps here: https://jpmtech.io/apps. Thank you for taking the time to check out my work!