I am trying to change Navbar background color that will be push in navigation stack. I am using navigation controller under Tabbar controller. When I push view controller after changing the navbar color, in first attempt it does not work. when i reload this view by tapping tabbar item it works.
Why it is not working in first attempt?
view controller called from another Viewc controller
func showProjectDetails(indexPath: IndexPath) {
let vc = storyboard?.instantiateViewController(withIdentifier: "MyTaskVC") as! MyTaskVC
vc.viewMode = .ProjectDetails
vc.currentProjectName = projects[indexPath.row].projectName
navigationController?.pushViewController(vc, animated: true)
}
view conroller that pushed
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let appearance = UINavigationBarAppearance()
appearance.backgroundColor = .green
appearance.titleTextAttributes = [.foregroundColor: UIColor.white]
appearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().compactAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
}
Add this code in your viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
if let navigationBar = navigationController?.navigationBar {
let appearance = UINavigationBarAppearance()
appearance.backgroundColor = .green
appearance.titleTextAttributes = [.foregroundColor: UIColor.red]
appearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
let barAppearence = UIBarButtonItemAppearance()
barAppearence.normal.titleTextAttributes = [.foregroundColor: UIColor.yellow]
appearance.buttonAppearance = barAppearence
navigationBar.scrollEdgeAppearance = appearance
navigationBar.compactAppearance = appearance
navigationBar.standardAppearance = appearance
// Do any additional setup after loading the view.
}
}
You should create a subclass of UINavigationController and customize it, if you are using Interface Builder, you can set the NavigationController custom class in the Identify Inspector.
import UIKit
class YourNavigationController: UINavigationController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let barAppearance = UINavigationBar.appearance(whenContainedInInstancesOf: [YourNavigationController.self])
barAppearance.tintColor = UIColor(named: "Blue"
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
You can read more here
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.