Reputation: 7210
I want to change the color of the UINavigationBar, per the view controller in my stack of view controllers. As in, a way that I can tell a view controller to seque and then change the navigation bar color. The only issue is when I try to seque; the navigation color stays the same from the previous view controller. My code in my first VC's viewDidLoad is:
if let navController = self.navigationController {
navController.navigationBar.tintColor = UIColor.whiteColor()
navController.navigationBar.barTintColor = UIColor.blackColor()
navController.navigationBar.translucent = false
navController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.blackColor()]
}
Then in my next VC I want to inver that to be
if let navController = self.navigationController {
navController.navigationBar.tintColor = UIColor.blackColor()
navController.navigationBar.barTintColor = UIColor.whiteColor()
navController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.blackColor()]
}
I tried to invert it on the viewDidDissapear; but that just looked glitchy. What am I doing wrong?
Upvotes: 2
Views: 1787
Reputation: 36
Customize your view controllers' navigation bars in the -viewWillAppear method of each view controller!
This will prevent any glitchy appearance, like you mentioned -viewDidDisappear did, because it will be called right before each view controller loads (before the user sees the loaded views).
Upvotes: 1
Reputation: 71854
I have tested your code and it is working fine for me here is my code:
FirstViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let navController = self.navigationController {
navController.navigationBar.tintColor = UIColor.whiteColor()
navController.navigationBar.barTintColor = UIColor.redColor()
navController.navigationBar.translucent = false
navController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.blackColor()]
}
}
//Add this code if you want same color for when you come back to your first viewController
override func viewWillAppear(animated: Bool) {
if let navController = self.navigationController {
navController.navigationBar.tintColor = UIColor.whiteColor()
navController.navigationBar.barTintColor = UIColor.redColor()
navController.navigationBar.translucent = false
navController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.blackColor()]
}
}
}
SecondViewController.swift
import UIKit
class SViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let navController = self.navigationController {
navController.navigationBar.tintColor = UIColor.blackColor()
navController.navigationBar.barTintColor = UIColor.greenColor()
navController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.blackColor()]
}
}
}
And HERE is sample project.
Upvotes: 3