swiftui

Customize font style for large navigation bar title in SwiftUI


I am using the large navigation bar title in a SwiftUI view. How can I set a .serif and .black font style for the navigation bar tile?

Unfortunately I cannot modify attributes when setting the navigationBarTitle

enter image description here`

enter image description here


Solution

  • The one way I know is to change the appearance of NavigationBar in the whole app.

    You can do this by calling this code:

    let largeTitle = UIFont.preferredFont(forTextStyle: .extraLargeTitle)
    let regularTitle = UIFont.preferredFont(forTextStyle: .body)
    
     // Define descriptor with rounded design
    let descriptor = largeTitle.fontDescriptor.withDesign(.rounded)!
    let largeFont = UIFont(descriptor: descriptor, size: largeTitle.pointSize)
    let regularFont = UIFont(descriptor: descriptor, size: regularTitle.pointSize)
    
    // For large title
    UINavigationBar.appearance().largeTitleTextAttributes = [.font : largeFont]
    
    // For inline title
    UINavigationBar.appearance().titleTextAttributes = [.font : regularFont]
    

    The important part here is to instantiate a font descriptor which you can setup whatever you like.

    Though, right how I mentioned at the beginning this will change navigation bar appearance in the whole app.

    Serif Rounded
    Serif large Rounded large
    Serif inline Rounded inline