简体   繁体   中英

How to dynamically change navigation bar color on ios15?

What worked for years was

self.navigationController?.navigationBar.barTintColor = MY_COLOR

but in iOS15 this is not working. There's answers for how to change it on app start:

if #available(iOS 15, *) {
    let appearance = UINavigationBarAppearance()
    appearance.configureWithOpaqueBackground()
    appearance.backgroundColor = MY_COLOR
    appearance.titleTextAttributes = [.foregroundColor: UIColor.white]
    UINavigationBar.appearance().standardAppearance = appearance
    UINavigationBar.appearance().scrollEdgeAppearance = appearance
    UINavigationBar.appearance().overrideUserInterfaceStyle = .dark
}

but this doesn't work when I run it outside of AppDelegate. I need to be able to change the color dynamically in a given ViewController after it's been loaded and shown the same way I can change the title.

You could call a reference to your appDelegate and then call the method off of it:

In one of your VCs:

let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.yourMethod()

In your AppDelegate.swift:

func yourMethod()
{
   if #available(iOS 15, *) {
      let appearance = UINavigationBarAppearance()
      appearance.configureWithOpaqueBackground()
      appearance.backgroundColor = MY_COLOR
      appearance.titleTextAttributes = [.foregroundColor: UIColor.white]
      UINavigationBar.appearance().standardAppearance = appearance
      UINavigationBar.appearance().scrollEdgeAppearance = appearance
      UINavigationBar.appearance().overrideUserInterfaceStyle = .dark
    }
 }

You can also pass the colour as an argument, I suppose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM