I'm building a social network that allows users to navigate from one profile to the next, by viewing who they follow. For simplicity, I created a test project with two view controllers: ViewController
and SecondViewController
.
Each view controller has a button that fires an IBAction to instantiate the next view controller. That view is then pushed on the navigation stack. A user can do this as long as there is another viewController to push. But when they start returning/popping is when I have issues.
Here's ViewController:
class ViewController: UIViewController {
@IBOutlet weak var pageNumberLabel: UILabel!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.title = "First"
setUp()
}
func setUp() {
print("Setup 1")
let navBarAppearance = self.navigationController!.navigationBar
navBarAppearance.setBackgroundImage(UIImage(), for: .default)
navBarAppearance.shadowImage = UIImage()
navBarAppearance.barStyle = .black
navBarAppearance.isTranslucent = true
navBarAppearance.tintColor = .white
navBarAppearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white]
self.navigationController?.view.backgroundColor = UIColor.lightGray
}
@IBAction func pushSecondViewController() {
if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "secondVC") as? SecondViewController {
print("-")
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
Here's SecondViewController:
class SecondViewController: UIViewController {
@IBOutlet weak var pageNumberLabel: UILabel!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.title = "Second"
setUp()
}
func setUp() {
print("Setup 2")
let navBarAppearance = self.navigationController!.navigationBar
navBarAppearance.isTranslucent = false
navBarAppearance.barTintColor = .white
navBarAppearance.tintColor = .blue
navBarAppearance.barStyle = .black
navBarAppearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.blue]
}
@IBAction func pushFirstViewController() {
if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "firstVC") as? ViewController {
print("-")
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
When SecondViewController is popped and ViewController is presented, the navigationTitle stays UIColor.blue. However, if I swipe from SecondViewController to ViewController, the title correctly changes colors.
Why is this?