DEV Community

ShoheOhtani
ShoheOhtani

Posted on

3 1

[SwiftUI] How to set custom font to NavigationBarTitle

Image description

You need to install Introspect library.

How to use

It should be used on root of navigationView. If you use



NavigationView {
    VStack { ... }
        // ↓ set custom font
        .navigationTitleFont(font: UIFont.custom.extraBold(ofSize: 20))
}


Enter fullscreen mode Exit fullscreen mode

3 Steps

  1. Create ViewModifier
  2. Add extension method to UIFont
  3. Add extension method to View

Step1: Create ViewModifier



import SwiftUI
import Introspect

public struct NavigationTitleFontModifier: ViewModifier {
    public var font: UIFont

    public func body(content: Content) -> some View {
        content
            .introspectNavigationController {
                $0.navigationBar.titleTextAttributes = [.font:font]
            }
    }
}


Enter fullscreen mode Exit fullscreen mode

Step2: Add extension method to UIFont
This is unnecessary. It just for make call custom font easily.



extension UIFont {
    public struct custom {
        static func extraBold(ofSize size: CGFloat) -> UIFont {
            return UIFont(name: "BoldCustomFontName", size: size) ?? UIFont.systemFont(ofSize: size, weight: .bold)
        }
    }
}


Enter fullscreen mode Exit fullscreen mode

Step3: Add extension method to View



public extension View {
    func navigationTitleFont(font: UIFont) -> some View {
        self.modifier(NavigationTitleFontModifier(font: font))
    }
}


Enter fullscreen mode Exit fullscreen mode

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay