Robert Petit
Robert Petit

Reputation: 23

Custom background color for UINavigationBar using SwiftUI

I'm trying to use my own background color for UINavigationBar using SwiftUI but I'm not able to change it using the following code:

let attrs = [
     NSAttributedString.Key.foregroundColor: UIColor.blue,
     NSAttributedString.Key.font: UIFont(name: "AbrilFatface-Regular", size: 24)!]

UINavigationBar.appearance().titleTextAttributes = attrs
UINavigationBar.appearance().backgroundColor = UIColor(red:253/255, green:213/255, blue:211/255, alpha:1.0)

Upvotes: 2

Views: 267

Answers (1)

lacefarin
lacefarin

Reputation: 1234

Your code has nothing to do with SwiftUI. For changing UINavigationBar Appearance you must use UIKit which is predecessor of SwiftUI. The code bellow will change Navigation Bars globally.

// Instantiate new UINavigationBarAppearance object
let navigationBarAppearance = UINavigationBarAppearance()
// Set background colour
navigationBarAppearance.backgroundColor = .black
// Set text color for title
navigationBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]
// Set text color for large title
navigationBarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]

// Assign appearance
UINavigationBar.appearance().standardAppearance = navigationBarAppearance
UINavigationBar.appearance().compactAppearance = navigationBarAppearance
UINavigationBar.appearance().scrollEdgeAppearance = navigationBarAppearance

Call this in AppDelegate.swift file indside application(_:didFinishLaunchingWithOptions:) method. This code works for iOS 13+.

Here is the apple documentation for Legacy Customizations in case you need it.

Upvotes: 1

Related Questions