SwiftUI Font and Texts

In this article, I will show you how to use SwiftUI fonts for text views in your iOs apps. Typography and fonts play a fundamental role in UI/UX design, influencing the user experience and visual appeal of an app. You will learn how to maintain consistency, prioritize readability, establish visual hierarchy, test for accessibility, and embrace customization in your iOS apps. Additionally, I will demonstrate how to work with system fonts and customize them using SwiftUI. By following these guidelines, you will be able to leverage the power of fonts to create captivating and intuitive user interfaces.

The Importance of Typography and Fonts in UI/UX Design

Typography and fonts are crucial UI/UX design elements that greatly impact the user experience. They help set the mood, convey information, and make an app or website more enjoyable to use. Let’s take a recipe app’s detail view as an example to understand why typography and fonts matter.

Imagine a recipe app where you can find cooking instructions and ingredient lists. Now, let’s compare two versions of the app’s detail view: one with the default font and the other with carefully chosen font styles.

Swiftui example with and without font stylings
A recipe detail view: left shows only the default text styling and on the right texts where styled with font changes.
  1. The Default Font: In the first version, the app uses the font that comes with the device. It looks plain and doesn’t have any special style. The text may appear boring and make it difficult for users to find important information, like ingredient measurements or cooking steps.
  2. Font Styles: The app pays attention to typography in the second version. It selects fonts that match its style and the emotions it wants to evoke. For headings, it uses a clean and modern font to make them stand out and organized. For the main text, it chooses a readable and inviting font to make reading comfortable. The app also uses different font weights to show the importance of information. Recipe titles are in bold to catch attention, while the ingredient list and instructions use regular weight for easy reading.

By using these font styles, the second version of the detail view creates a more engaging user experience. The app looks visually appealing, making users want to explore further. The careful use of fonts helps users quickly find important information and makes the app easier to use.

Here are five tips for properly using fonts in iOS apps:

  1. Maintain Consistency: Consistency is key when using fonts in your iOS app. Choose a primary font or a font pairing that aligns with your app’s branding and stick to it throughout the app. Consistent font usage creates a cohesive and polished user experience.
  2. Consider Readability: Prioritize readability when selecting fonts for your app. Ensure that the chosen fonts are legible and easy to read, even in different text sizes or on various devices. Avoid overly decorative or intricate fonts that may hinder readability.
  3. Establish Visual Hierarchy: Use font styles, weights, and sizes to establish a visual hierarchy in your app’s interface. Differentiate headings, titles, and important information from regular text by using bolder weights or larger sizes. A clear visual hierarchy guides users and enhances the overall user experience.
  4. Test for Accessibility: Ensure that the fonts you choose are accessible to users with varying visual abilities. Test your app’s fonts with different accessibility settings, including dynamic type, to ensure that the text remains legible and doesn’t lose its clarity or spacing. Consider using font styles or sizing that can adapt to users’ accessibility preferences.
  5. Embrace Customization: While system fonts provide consistency across iOS devices, don’t be afraid to incorporate custom fonts when it aligns with your app’s branding and design goals. Custom fonts can add personality and uniqueness to your app. Just ensure that the custom fonts maintain readability and integrate seamlessly with the overall app design.

I hope I could motivate you in working with fonts and texts. They are a big part of the daily development work. Now let’s see how they are used in SwiftUI!

Free SwiftUI Layout Book

Get Hands-on with SwiftUI Layout.

Master SwiftUI layouts with real-world examples and step-by-step guide. Building Complex and Responsive Interfaces.

Working with System Fonts in SwiftUI

When working with fonts in SwiftUI, it’s a great starting point to use the available system fonts. This easily ensures consistency and adaption to accessibility settings. Here’s an example code snippet that demonstrates the use of system fonts in SwiftUI:

struct ContentView: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 20) {
            VStack(alignment: .leading, spacing: 20) {

                Text("Large Title").font(.largeTitle)
                Text("Title").font(.title)
                Text("Title2").font(.title2) // available iOS 14
                Text("Title3").font(.title3) // available iOS 14

                Divider()

                Text("Headline").font(.headline)
                Text("Subheadline").font(.subheadline)
            }

            Divider()

            VStack(alignment: .leading, spacing: 20) {
                Text("Body").font(.body)  // --> default font
                Text("Callout").font(.callout)
                Text("Footnote").font(.footnote)
                Text("Caption").font(.caption)
                Text("Caption2").font(.caption2) // available iOS 14
            }
        }
    }
}

In this code, I utilize various font styles available through the system fonts in SwiftUI. The font modifier is applied to different Text views, using the designated font names provided by SwiftUI. Here’s a breakdown of the font styles used in the code:

  • largeTitle, title, title2, title3: These are larger font styles suitable for headings and titles, with variations available in iOS 14 and onwards.
  • headline and subheadline: These styles are useful for emphasizing important text elements such as headings or subheadings.
  • body: This is the default font style that maintains readability and is commonly used for the main body text.
  • callout, footnote, caption, caption2: These font styles cater to smaller text sizes, ideal for displaying additional information or captions.

These fonts adjust depending on the user’s settings. They scale appropriately for accessibility types.

swiftui example for system fonts in various accessibility setting
SwiftUI system fonts in different dynamic type sizes: from small, and large sizes to accessibility 2 and 5.
changing the text size in the iOS settings app
The user can change the text size in the Settings app.

You can access the dynamic type size settings in SwiftUI from the environment:

@Environment(\.dynamicTypeSize) var dynamicTypeSize

This is an enum with all of the values you can see above in the settings app:

switch dynamicTypeSize {
    case .xSmall:

    case .small:

    case .medium:

    case .large:

    case .xLarge:

    case .xxLarge:

    case .xxxLarge:

    case .accessibility1:

    case .accessibility2:

    case .accessibility3:

    case .accessibility4:

    case .accessibility5:

}

You can also check if ´larger accessibility sizes´ is enabled:

dynamicTypeSize.isAccessibilitySize

How to customize system fonts in SwiftUI

In SwiftUI, you have the flexibility to customize system fonts to suit your app’s design and branding. Let’s explore how you can modify and customize system fonts in SwiftUI.

Font Design and Font Size

SwiftUI provides different font sizes that you can apply to your text views. Use the .font(.system(size: 16)) modifier to set a specific font size, where 16 represents the desired size in points. You can also choose from 4 differnt font designs: default, serif, monospaced and rounded.

struct ContentView: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 20) {

         Text("design: .default size 18, font weigth medium")
             .font(.system(size: 18, weight: .regular, design: .default))

            Text("design: .default")
                .font(.system(.body, design: .default))

            Text("design: .serif")
                .font(.system(.body, design: .serif))

            Text("design: .monospaced")
                .font(.system(.body, design: .monospaced))

            Text("design: .rounded")
                .font(.system(.body, design: .rounded))

            Text("design: .rounded, font weight: heavy")
                .font(.system(.body, design: .rounded))
                .fontWeight(.heavy)
        }
    }
}
swiftui font weight examples

A new view modifier is the .font(.system(size: 18, weight: .regular, design: .default)) which allows you to simultaneously set the font weight. This is available since iOS 16 and macOS 13.

You can also set the font-weight with another view modifier, which I am going to show you in the next section.

Changing the Font Weight

You can adjust the weight of the system font to create visual hierarchy and emphasize specific text elements. For example, you can use the .fontWeight(.bold) modifier to make a text bold and more prominent. A shorter form for bold text is the bold view modifier:

Text("bold").bold() // new .bold(false)

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

New for iOS 16 is the possibility to toggle the font-weight:

@State private var isBold = false

Text("bold").bold(isBold)
Button("Make Bold") {
   isBold.toggle()
}

All other font weights than bold can be set with the fontWeight view modifier:

struct ContentView: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 20) {
            Text("Ultra Light Font")
                .fontWeight(.ultraLight)
            Text("Thin Font")
                .fontWeight(.thin)
            Text("Light Font")
                .fontWeight(.light)
            Text("Regular Font")
                .fontWeight(.regular)
            Text("Medium Font")
                .fontWeight(.medium)
            Text("Semibold Font")
                .fontWeight(.semibold)
            Text("Bold Font")
                .fontWeight(.bold)
            Text("Heavy Font")
                .fontWeight(.heavy)
            Text("Black Font")
                .fontWeight(.black)
        }
        .padding().padding(.bottom, 300)
    }
}
Example to change the font weight in Swiftui

Further Finetuning of SwiftUI Text Appearance

You can also modify the style of the system font. For example, the .italic() modifier can be applied to make the text appear italicized, while .underline() adds an underline to the text.

Text("Italicized Text")
   .italic()
Text("Underlined Text")
   .underline()
Text("Strikethrough Text")
   .strikethrough()

New with iOS 16 and macOS 13 is the possibility to change the pattern and foreground color of the line used in  .underline() and  .strikethrough() :

Text("pattern       dot")
    .strikethrough(pattern: .dot)
Text("color pink")
   .strikethrough(pattern: .dash color: .pink)
Text("pattern dot")
   .underline(pattern: .dot, color: .accentColor)

There are 4 options for the patter: solid, dash, dot, and dashDot.

SwiftUI examples for customizing Text

Changing Font Spacing and Positioning in SwiftUI

In SwiftUI, you have control over the spacing and positioning of text elements, allowing you to fine-tune the typography and create visually appealing layouts. Let’s explore how you can change font spacing using different modifiers in SwiftUI:

Monospaced digits ensure consistent character widths, which can be helpful when displaying numerical values. By applying the `.monospacedDigit()` modifier to a `Text` view, you enforce a fixed width for digits, enhancing readability. Here’s an example:

HStack {
    VStack(alignment: .leading) {
        Text("default")
        Text("monospacedDigit").monospacedDigit()
    }

    VStack(alignment: .leading) {
        Text("1234567890")
        Text("1234567890").monospacedDigit()
    }
}

In this code snippet, the second `Text` view with “monospacedDigit” applies the `.monospacedDigit()` modifier to ensure consistent digit widths.

Kerning adjusts the spacing between individual characters to enhance the visual appeal or achieve a specific design effect. In SwiftUI, you can control the kerning using the `.kerning(_:)` modifier. Here’s an example:

Text("Kerning Text - 2")
.kerning(2)

In this code snippet, the .kerning(_:) modifier is used to adjust the spacing between characters in the Text views. The value passed (2) determines the amount of spacing applied.

Similar to kerning, tracking modifies the overall spacing between characters but on a wider scale. The `.tracking(_:)` modifier is used to adjust the tracking of a `Text` view. Here’s an example:

Text("Tracking Text - 2")
.tracking(2)

In this code snippet, the `.tracking(_:)` modifier adjusts the overall character spacing in the `Text` views. The value passed (2) determines the amount of spacing applied.

Baseline offset changes the vertical positioning of text, shifting it up or down relative to the baseline. You can use the `.baselineOffset(_:)` modifier to adjust the baseline offset of a `Text` view. Here’s an example:

HStack {
        Text("some text")
        Text("baselineOffset").baselineOffset(15)
        Text("set")
        Text("to").baselineOffset(15).underline()
        Text("15").underline()
}

In this code snippet, the `.baselineOffset(_:)` modifier is used to vertically offset the selected `Text` view.

The above example uses a HStack with a default alignment of center. If you want to align the text to the baseline use:

HStack(alignment: .firstTextBaseline) {
        Text("some text")
        Text("baselineOffset").baselineOffset(15)
        Text("set")
        Text("to").baselineOffset(15).underline()
        Text("15").underline()
}

New with iOS 16 and macOS 13 is the text fontWidth modifier. This stretches or compresses the system font vertically:

HStack(alignment: .firstTextBaseline) {
    Text("set text width")

    VStack(alignment: .leading, spacing: 5) {
        Text("expanded")
            .fontWidth(.expanded)
        Text("standard")
            .fontWidth(.standard)
        Text("condensed")
            .fontWidth(.condensed)
        Text("compressed")
            .fontWidth(.compressed)
    }
}
Free SwiftUI Layout Book

Get Hands-on with SwiftUI Layout.

Master SwiftUI layouts with real-world examples and step-by-step guide. Building Complex and Responsive Interfaces.

How to use custom Fonts in Xcode

In SwiftUI, you have the ability to incorporate custom fonts into your app’s design, allowing you to create a unique and personalized typography style. Here are examples of how to use them in SwiftUI:

Text("American Typewriter")
    .font(.custom("AmericanTypewriter", size: 18))
Text("Copperplate")
    .font(.custom("Copperplate", size: 18))
Text("Cochin font - fixedSize 18")
    .font(.custom("Cochin", fixedSize: 18)) // available iOS 14 and macOS 11
Text("Cochin font - size 18")
    .font(.custom("Cochin", size: 18))
Text("Cochin font - fixedSize 18 - relativeTo body")
    .font(.custom("Cochin", size: 18, relativeTo: .body)) // available iOS 14 and macOS 11

Use the .font(.custom("FontName", size: 18)) modifier, where “FontName” is the exact name of the custom font. Adjust the size value as desired. These will also adopt the font size to the dynamic type size. However, if you want to use a fixed font size, you can use the new modifier:

.font(.custom("Cochin", fixedSize: 18)) // available iOS 14 and macOS 11
swiftui fonts with different families and accessibility

You can find all fonts that are preinstalled and available in the macOS Font Book app. Open the Font Book application on your Mac and locate the font you want to use. Select the font and click on the info button. In the trailing sidebar, you’ll find the PostScript name of the font. Make a note of this name and use it with the SwiftUI font modifier.

Finding preinstalled fonts for macOS in the font book app
You can find preinstalled fonts for macOS in the font book app. If they are system fonts, you can use them directly in your Xcode projects.

Not all fonts can be fully customised. For example Helvetica new has 14 font weights, you can find them in the font book app in the toolbar. Here is an example:

Text("HelveticaNeue")
     .font(.custom("HelveticaNeue", size: 18))
     .fontWeight(.black)

Adding Custom Fonts to Xcode

In SwiftUI, you have the ability to incorporate custom fonts into your app’s design, allowing you to create a unique and personalized typography style. Here’s a step-by-step guide on how to use custom fonts in SwiftUI:

  1. Add Custom Font Files to Your Xcode Project: Start by adding the custom font files (typically in .ttf or .otf format) to your Xcode project. Drag and drop the font files into your project navigator, ensuring that “Copy items if needed” is selected.
  2. Register the Fonts in Your App’s Info.plist: To make the custom fonts accessible to your app, you need to register them in the Info.plist file. Open the Info.plist file and add a new entry called “Fonts provided by application” (or “UIAppFonts” if you prefer the raw key). Under this entry, add an item for each custom font file you’ve added, specifying the filename, including the file extension.
  3. Verify the Font Names: It’s important to verify the exact font names that SwiftUI expects. Open the custom font files in Font Book (on macOS) or Font Viewer (on Windows), and make a note of the PostScript name or the font family name.

Creating Font Modifiers for Consistency

To maintain consistency in your typography across different parts of your app, creating custom font modifiers can be a valuable approach. Let’s explore how you can create font modifiers for consistent styling using the headers in a Recipe Detail View as an example:

Text("Ingredients")
    .font(.system(size: 20, weight: .bold, design: .serif))
    .underline(color: .gray)
    .foregroundColor(Color("lightGreyText"))

Text("Instructions")
    .font(.system(size: 20, weight: .bold, design: .serif))
    .underline(color: .gray)
    .foregroundColor(Color("lightGreyText"))

The headers “Ingredients” and “Instructions” are styled using a specific font, underline, and foreground color. Instead of repeating the same modifiers for each header, you can create a reusable view modifier that encapsulates the desired styling.

Here’s an example of creating a custom view modifier for consistent header styling:

struct RecipeDetailView_Previews: PreviewProvider {
    static var previews: some View {
        RecipeDetailView()
    }
}
struct HeaderStyle: ViewModifier {
    func body(content: Content) -> some View {
        content
            .font(.system(size: 20, weight: .bold, design: .serif))
            .underline(color: .gray)
            .foregroundColor(Color("lightGreyText"))
    }
}

To apply the custom header style, you can simply use the headerStyle modifier:

Text("Ingredients")
    .headerStyle()

Text("Instructions")
    .headerStyle()

By applying the HeaderStyle view modifier, you achieve consistent styling for the headers across different parts of your app. Any changes or updates to the header styling can be done in one place, making it easier to maintain and ensure consistency throughout your app.

Creating custom view modifiers for font styles, colors, or other common styling elements in your app can serve as a style guide, promoting consistency and reducing repetitive code. This approach helps streamline your development process and ensures a cohesive visual experience for your users.

Consider applying this approach to other common styling elements in your app to establish a comprehensive style guide, making it easier to maintain and evolve your app’s design.

Conclusion

Typography and fonts are vital for UI/UX design, impacting the user experience. I gave you an example with a recipe app’s detail view. I showed you how to use and style text views in SwiftUI.

To properly use fonts in iOS apps, consider the following tips:

Firstly, maintain consistency by selecting a primary font or font pairing that aligns with your app’s branding. Secondly, prioritize readability by choosing legible fonts and avoiding overly decorative styles. Establish visual hierarchy using font styles, weights, and sizes to differentiate headings and important information from regular text. Test your app’s fonts for accessibility, ensuring they remain legible in different settings. Lastly, embrace customization by incorporating custom fonts that align with your app’s design goals while maintaining readability and integration.

SwiftUI offers various options to customize fonts, including font size, weight, and style modifications. Additionally, you can adjust font spacing using modifiers such as monospacedDigit(), kerning(), tracking(), and baselineOffset().

By following these guidelines, you can effectively utilize fonts in your iOS app, enhancing the user experience and creating a visually appealing interface.

Further Reading:

4 thoughts on “SwiftUI Font and Texts”

  1. What’s Happening i’m new to this, I stumbled upon this I’ve discovered It absolutely helpful and it has helped me out
    loads. I am hoping to give a contribution & assist different users like its aided
    me. Great job.

    Reply
  2. Hello there! This post couldn’t be written any better!
    Reading this post reminds me of my good old room mate! He always
    kept talking about this. I will forward this page to him.
    Fairly certain he will have a good read. Thanks for sharing!

    Reply

Leave a Comment

Subscribe to My Newsletter

Want the latest iOS development trends and insights delivered to your inbox? Subscribe to our newsletter now!

Newsletter Form

New Course Announcement!!!

50% OFF Launch Sale

MacOS Development with SwiftUI