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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)