Swift and SwiftUI tutorials for Swift Developers

How to change font and color in a Navigation Bar in SwiftUI

Currently, SwiftUI does not provide a direct modifier to set the font and color of the navigation bar. However, we can use the UINavigationBarAppearance API provided by UIKit to achieve this customization.

To change the title color to red and the font to Arial Rounded MT Bold, we can create a UINavigationBarAppearance object in the init() function and set the desired attributes. Insert the following function into the ContentView:

init() {
        let navBarAppearance = UINavigationBarAppearance()
        navBarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.red, .font: UIFont(name: "ArialRoundedMTBold", size: 35)!]
        navBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.red, .font: UIFont(name: "ArialRoundedMTBold", size: 20)!]
        
        UINavigationBar.appearance().standardAppearance = navBarAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = navBarAppearance
        UINavigationBar.appearance().compactAppearance = navBarAppearance
        
    }

The code in XCode would look like this:

The largeTitleTextAttributes property is used to set the large-sized title text attributes, while the titleTextAttributes property is used to set the standard-sized title text attributes. Once we have set the navBarAppearance, we assign it to the three appearance properties: standardAppearance, scrollEdgeAppearance, and compactAppearance.

If you want, you can create separate appearance objects for scrollEdgeAppearance and compactAppearance and assign them individually.

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Article

How to use NavigationStack in SwiftUI

Next Article

How to change the back button image and color in SwiftUI

Related Posts