Charlie Maréchal
Charlie Maréchal

Reputation: 175

How can I use SF Pro Rounded or a custom Font for Navigation titles in SwiftUI?

I am trying to change the font for the Navigation View title to the system rounded one, but I can't seem to find a way to do it.

To be clear, I can change the font fine on any Text View, List etc, but on the Navigation Title it seems to be impossible.

For reference the title ("Settings") in the app Carrot Weather achieves this: enter image description here

Any idea?

Thanks !!!

Upvotes: 4

Views: 2525

Answers (1)

aheze
aheze

Reputation: 30436

You can use largeTitle to get the default navigation bar font, then apply rounding using withDesign(_:).

struct ContentView: View {
    init() {
        var titleFont = UIFont.preferredFont(forTextStyle: .largeTitle) /// the default large title font
        titleFont = UIFont(
            descriptor:
                titleFont.fontDescriptor
                .withDesign(.rounded)? /// make rounded
                .withSymbolicTraits(.traitBold) /// make bold
                ??
                titleFont.fontDescriptor, /// return the normal title if customization failed
            size: titleFont.pointSize
        )
        
        /// set the rounded font
        UINavigationBar.appearance().largeTitleTextAttributes = [.font: titleFont]
    }
    var body: some View {
        NavigationView {
            Text("Hello World!")
                .navigationTitle("Dashboard") /// use this for iOS 14+
        }
    }
}

Result:

Rounded navigation bar title

Upvotes: 10

Related Questions